首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较postgreSQL表中的行,并保留列中字符串最长的行

比较postgreSQL表中的行,并保留列中字符串最长的行
EN

Stack Overflow用户
提问于 2020-07-14 15:45:22
回答 2查看 31关注 0票数 0

我在PostgreSQL 11.0中有以下表格

代码语言:javascript
复制
id      col1                             col2           code
3876    dexamethasone                   dexamethasone   A01AC | C05AA | D07AB | S01BA
3948    dexamethasone sodium phosphate  dexamethasone   A01AC | C05AA 
187834  dexamethasone sodium succinate  dexamethasone   H02AB | S01BA
352241  dexamethasone acetate           dexamethasone   D07AB | H02AB | S01BA
971608  dexamethasone phosphate         dexamethasone   H02AB
1010    insulin plus                    insulin         H02ABA | H02ABC
10101   paracet                         insul           H02A
10101   paracetamol                     insul           H02A

如果各行的col2值相同,而id值不同,我希望保留代码字符串最长的行(或id的最小值)。其余行保持不变。

所需的输出为:

代码语言:javascript
复制
id      col1                             col2           code
3876    dexamethasone                   dexamethasone   A01AC | C05AA | D07AB | S01BA
1010    insulin plus                    insulin         H02ABA | H02ABC
10101   paracet                         insul           H02A
10101   paracetamol                     insul           H02A

对于这个问题,我没有可以尝试的起点。非常感谢您的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-14 17:16:44

db-fiddle here

代码语言:javascript
复制
with dup_ids as (
  select id
    from codes
   group by id
  having count(*) > 1
)
select distinct on (c.col2||case when d.id is null then '' else c.col1 end) c.*
  from codes c
  left join dup_ids d on d.id = c.id
 order by (c.col2||case when d.id is null then '' else c.col1 end), length(c.code) desc, c.id;
票数 0
EN

Stack Overflow用户

发布于 2020-07-14 18:04:28

如果我没看错的话,您可以使用distinct onrow_number()

代码语言:javascript
复制
select distinct on (
    col2, 
    row_number() over(partition by col2, id order by id)
) t.*
from mytable t
order by
    col2, 
    row_number() over(partition by col2, id order by id),
    length(code) desc, 
    id
;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62890325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档