Postgres查询将具有相同列值的多行合并为单行

问题描述 投票:-1回答:2

我有这张桌子:

enter image description here

并且想要将其转换为以下内容:

enter image description here

[请帮助我,坚持太久了。使用分组依据对我不起作用

sql postgresql select group-by
2个回答
0
投票
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;

0
投票

对于此数据集,简单的聚合将满足您的要求:

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

这利用了聚合函数忽略null值的事实;我们可以使用max()获得与使用min()相同的结果。

© www.soinside.com 2019 - 2024. All rights reserved.