按列进行分组,并在另一列中获取最大长度的字符串的行。

问题描述 投票:1回答:1

我在Postgres 11中有以下表格。

table1:

id          col1    col2                        col3                        col4                        
NCT00000374 Drug    olanzapine                  olanzapine                  olanzapine                  
NCT00000390 Drug    imipramine hydrochloride    imipramine hydrochloride    imipramine hydrochloride    
NCT00000390 Drug    imipramine hydrochloride    imipramine hydrochloride    imipramine                  
NCT00000412 Drug    placebo calcitriol          placebo calcitriol          calcitriol                  

我想获取每行的最大长度值。(id, col1, col2, col3).

所需的输出是。

id          col1    col2                        col3                        col4                        
NCT00000374 Drug    olanzapine                  olanzapine                  olanzapine                  
NCT00000390 Drug    imipramine hydrochloride    imipramine hydrochloride    imipramine hydrochloride    
NCT00000412 Drug    placebo calcitriol          placebo calcitriol          calcitriol                  

我试过下面的查询,但至今没有成功。

select * from table1
where length(col4) = max(length(col4))
group by id, col1, col2, col3
order by id
sql postgresql greatest-n-per-group aggregation
1个回答
1
投票

一个案例 DISTINCT ON:

SELECT DISTINCT ON (id, col1, col2, col3)
       *
FROM   table1
ORDER  BY id, col1, col2, col3, length(col4) DESC NULLS LAST;

最简单,每行的行数较少 (id, col1, col2, col3) 也是一般最快的。详细解释。

对于大表和每组很多行,有(更)快的技术。

© www.soinside.com 2019 - 2024. All rights reserved.