0
我有以下的表有三列:根据第三列的值,我如何在一列中进行聚合?
id | type | value
-----+------+-------
foo | bar | 123
foo | bar | 456
foo | biz | 789
foo | biz | 987
baz | bar | 555
quz | biz | 777
我试图在给定type
聚集value
,返回这样的结果:
id | bar | biz
-----+---------------+-----------
foo | {123,456} | {789,987}
baz | {555} | {}
quz | {} | {777}
我到目前为止已经试过自动加入表格两次(使用LEFT JOIN
来计算空列),然后执行DISTINCT
以在汇总之前删除重复项。有没有更好的办法?
目前查询:
SELECT
test.id,
ARRAY_REMOVE(ARRAY_AGG(DISTINCT(t1.value)), NULL) AS bar,
ARRAY_REMOVE(ARRAY_AGG(DISTINCT(t2.value)), NULL) AS biz
FROM test
LEFT JOIN test t1 ON test.id = t1.id AND t1.type = 'bar'
LEFT JOIN test t2 ON test.id = t2.id AND t2.type = 'biz'
GROUP BY test.id;