postgresql - 根据 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。
解决方案
你可以试试这样的
select min(col1) as col1 ,
col2,
col3,
string_agg(col4, ',')
from table
where col2 like '%dexamethasone%'
and col1 = 'Dexamethasone'
group by col2, col3;
推荐阅读
- php - Yii2-无法将模型从控制器传递到视图
- flask - Flask 不安分的预处理器“DELETE_RESOURCE”没有被调用
- javascript - 如何在数据库中存储数据 onclick 按钮?
- java - 如何查找对类的所有对象的所有调用
- regex - 为以下字符串生成正则表达式
- android - Facebook 提供商未配置。确保添加 `facebook_application_id` 字符串
- azure - Azure 广告应用程序权限
- marklogic - MarkLogic 负载平衡与 marklogic-client-api
- c++ - 专门为一个参数使用两个模板参数(C++ 模板)
- python-3.x - 如何创建可以通过更改变量结束的计时脚本?