首页 > 解决方案 > 根据 Postgres 中一列(每组)的不同值选择行

问题描述

我在 PostgreSQL 11 中有下表。

col1    col2                          col3          col4
3876    Dexamethasone                 Dexamethasone A01AC
3876    Dexamethasone                 Dexamethasone C05AA
3876    Dexamethasone                 Dexamethasone D07AB
3924    Dexamethasone                 Dexamethasone A01AD
3924    Dexamethasone                 Dexamethasone C05AB
3925    Dexamethasone sulphate        Dexamethasone A01AC
3925    Dexamethasone sulphate        Dexamethasone C05AA

我想获取具有不同值 col1、col2、col3 和聚合 col4 的行,如果 col1、col2、col3 相同,则取 col1 的第一个值。

所需的输出是:

col1    col2                    col3            col4
3876    Dexamethasone           Dexamethasone   A01AC | C05AA | D07AB | A01AD | C05AB
3925    Dexamethasone sulphate  Dexamethasone   A01AC | C05AA

我尝试了以下查询。

select distinct on (col1, col2, col3) 
        col1, 
        col2, 
        col3, 
        string_agg(col4, ',') 
from table
where col2 ilike '%dexamethasone%' and col1 = 'Dexamethasone'
group by col1, col2, col3;

如何限制输出以使每个 col2、col3 获得一个 col1 值 .. 例如。选择 col1 值:3876 并排除 3924。

标签: postgresql

解决方案


你可以试试这样的

select min(col1) as col1 , 
                    col2, 
                    col3, 
                    string_agg(col4, ',') 
               from table 
               where col2 like '%dexamethasone%' 
                        and col1 = 'Dexamethasone' 
               group by col2, col3;

尝试在 postgres 中逐句阅读。


推荐阅读