簡體   English   中英

按列分組並在另一列中獲取具有最大字符串長度的行

[英]Group by columns and fetch rows with maximum length of string in another column

我在 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)具有最大長度值的行。

所需的 output 是:

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

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)通常也最快。 詳細解釋:

對於大表和每組多行,有(很多)更快的技術:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM