如何根据第三列的值聚合列?

时间:2017-08-08 18:30:37

标签: postgresql

我的下表有三列:

  id | type | value
-----+------+-------
 foo | bar  | 123
 foo | bar  | 456
 foo | biz  | 789
 foo | biz  | 987
 baz | bar  | 555
 quz | biz  | 777

我尝试在给定value内汇总type,返回如下结果:

 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;

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT id,
       ARRAY_REMOVE( Array_agg( bar ), NULL ) as bbar,
       ARRAY_REMOVE( Array_agg( biz ), NULL ) as bbiz
FROM (
   SELECT id, 
     CASE WHEN type = 'bar' THEN value ELSE NULL END AS bar,
     CASE WHEN type = 'biz' THEN value ELSE NULL END AS biz
   FROM test 
) x
GROUP BY id