PostgreSQL pivot:聚合函数调用可能不是嵌套错误

时间:2014-11-12 12:33:48

标签: sql postgresql pivot

我正在尝试使用CASE在postgreSQL中透视表,如本答案所示:https://stackoverflow.com/a/3008742/3063339。示例表:

CREATE TABLE scrap_pivot (event int, user_id text);
INSERT INTO scrap_pivot (event, user_id) VALUES
 (1, 'A')
,(2, 'A')
,(1, 'B')
,(3, 'B')
,(1, 'C')
,(2, 'D')
,(3, 'D');

但是,查询如下:

SELECT user_id,
SUM(CASE event WHEN 1 THEN count(user_id) ELSE 0 END) AS one,
SUM(CASE event WHEN 2 THEN count(user_id) ELSE 0 END) AS two,
SUM(CASE event WHEN 3 THEN count(user_id) ELSE 0 END) AS three,
FROM scrap_pivot
GROUP BY user_id;

返回错误:

ERROR: aggregate function calls may not be nested

根据原因和任何可能的解决方法的任何见解?当然,我可以将查询拆分为两个子查询,一个用于CASE,另一个用于SUM,但这会大大破坏大型表的性能。谢谢!

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

SELECT user_id,
       SUM(CASE event WHEN 1 THEN 1 ELSE 0 END) AS one,
       SUM(CASE event WHEN 2 THEN 1 ELSE 0 END) AS two,
       SUM(CASE event WHEN 3 THEN 1 ELSE 0 END) AS three,
FROM scrap_pivot
GROUP BY user_id;

如错误消息所示,您无法嵌套聚合函数。相反,您只需要条件聚合。