简体   繁体   中英

Postgres query to combine multiple rows with same value of a column into a single row

I have this table:

在此处输入图像描述

and would like to convert it to the following:

在此处输入图像描述

Please help me, been stuck on it for way too long. Doesn't working for me using group by

WITH A as (SELECT id, a FROM XXX WHERE a is not null),
     B as (SELECT id, b FROM XXX WHERE b is not null)
SELECT A.a, B.b, A.id FROM A 
     INNER JOIN B on A.id = B.id;

For this dataset, simple aggregation would do what you want:

select min(a) a, min(b) b, id
from mytable
group by id

This takes advantage of the fact that aggregate functions ignore null values; we could get the very same result with max() as we did with min() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM