我的查询
Select ID,string_agg(doc_id,',') from table group by ID;
这给了我
ID DOC_ID
123 01,02,03
456 01
789 02
100 01,03
现在我不希望doc_id的数据为01和02.但是如果01和02与其他doc_id一起出现,那么我想在我的外面
现在我跑步的时候
Select ID,string_agg(doc_id,',') from table group by ID,doc_id having doc_id not in (02,03) ;
它没有给我什么,而我期待
ID DOC_ID
123 01,02,03
100 01,03
那么如何用字符串agg给出条件?
几种潜在的方式......
首先,只消除聚合只有'01'或'02'的结果:
select
id, string_agg (doc_id, ',')
from table
group by id
having
array_agg (doc_id) not in ('{01}', '{02}')
或者,您可以使用其他逻辑,例如,如果计数大于1(因此它不能只是'01'或'02')或单个结果不是'01'或'02':
select
id, string_agg (doc_id, ',')
from table
group by id
having
count (*) > 1 or
min (doc_id) not in ('01', '02')
'min'有效,因为此时count> 1失败,你知道你只有一个元素......所以min将是那个元素的结果。