根据id合并多个bytea行

时间:2018-01-11 19:45:28

标签: database postgresql subquery

我正在使用postgres数据库,我需要根据ID将多行合并为一行。

ID  | A  | B  | C  |
--------------------
1   | x  |    |    |
1   | x  | y  |    |
2   | x  |    | z  |
3   |    | y  |    |
3   |    |    | z  |

A,B和C是bytea列。

我需要按如下方式合并:

ID  | A  | B  | C  |
--------------------
1   | x  | y  |    |
2   | x  |    | z  |
3   |    | y  | z  |

当我对ID执行GROUP BY时会出现问题,因为我无法为bytea列找到合适的聚合函数。

1 个答案:

答案 0 :(得分:2)

您可以随时使用子查询

WITH allID as ( 
    SELECT distinct ID
    FROM YourTable
)
SELECT 
   ID, 
  (SELECT A FROM yourTable yt where yt.ID = ai.ID ORDER BY A LIMIT 1) as A,
  (SELECT B FROM yourTable yt where yt.ID = ai.ID ORDER BY B LIMIT 1) as B,
  (SELECT C FROM yourTable yt where yt.ID = ai.ID ORDER BY C LIMIT 1) as C
FROM allID as ai