我正在尝试聚合ID上的值。如果它们完全相同,我会退回它们,但必须创造另一个价值' C'如果两者都遇到了。
CREATE TABLE foo ( fooid int, foocomm text ); INSERT INTO foo (fooid,foocomm) VALUES (1,'A'); INSERT INTO foo (fooid,foocomm) VALUES (1,'B'); INSERT INTO foo (fooid,foocomm) VALUES (2,'A');
SELECT
CASE
WHEN array_remove(array_agg(foocomm),NULL) = {'A'} THEN 'A'
WHEN array_remove(array_agg(foocomm),NULL) = {'B'} THEN 'B'
WHEN array_remove(array_agg(foocomm),NULL) = {'A','B'} THEN 'C'
END AS BAR
FROM foo
GROUP BY fooid;
它应该产生
fooid,foocomm
1, 'C'
2, 'A'
答案 0 :(得分:0)
t=# SELECT fooid,
CASE
WHEN array_remove(array_agg(foocomm order by foocomm),NULL) = '{A}' THEN 'A'
WHEN array_remove(array_agg(foocomm order by foocomm),NULL) = '{B}' THEN 'B'
WHEN array_remove(array_agg(foocomm order by foocomm),NULL) = '{A,B}' THEN 'C'
END AS BAR
FROM foo
GROUP BY fooid;
fooid | bar
-------+-----
1 | C
2 | A
(2 rows)
您的查询有效,只需修复数组文本表示:
https://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-INPUT