I have following table in 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
I would like to get rows with distinct values of col1, col2, col3 and aggregate col4 and take the first value of col1 if the col1, col2, col3 are identical.
The desired output is:
col1 col2 col3 col4
3876 Dexamethasone Dexamethasone A01AC | C05AA | D07AB | A01AD | C05AB
3925 Dexamethasone sulphate Dexamethasone A01AC | C05AA
I tried following query.
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;
How can I limit the output to get one col1 value per col2, col3.. for eg. selecting col1 value: 3876 and excluding 3924.
col1 = 3924
? Shouldn't there be an entry for this combination of values as well, and if not, then why not? – Tim Biegeleisendistinct on ()
doesn't really make sense when used with the same columns in thegroup by
– a_horse_with_no_name