我在PostgreSQL DB中有表
需要计算每个event_type
的计数总和(例如4和1)
当我使用这样的查询
SELECT account_id, date,
CASE
WHEN event_type = 1 THEN SUM(count)
ELSE null
END AS shows,
CASE
WHEN event_type = 4 THEN SUM(count)
ELSE null
END AS clicks
FROM widgetstatdaily WHERE account_id = 272 AND event_type = 1 OR event_type = 4 GROUP BY account_id, date, event_type ORDER BY date
我收到这张桌子
带有<null>
字段。这是因为我选择了event_type
,而我需要GROUP BY
。
如何使查询接收按account_id和日期结果分组的单元格中没有空值?喜欢(第一行)
272 2018-03-28 00:00:00.000000 57 2
也许我可以在收到结果后将其分组
答案 0 :(得分:2)
您需要条件聚合和其他一些修复程序。试试这个:
SELECT account_id, date,
SUM(CASE WHEN event_type = 1 THEN count END) as shows,
SUM(CASE WHEN event_type = 4 THEN count END) as clicks
FROM widgetstatdaily
WHERE account_id = 272 AND
event_type IN (1, 4)
GROUP BY account_id, date
ORDER BY date;
注意:
CASE
表达式应该是SUM()
的参数。ELSE NULL
是多余的。没有ELSE
的默认值为NULL
。WHERE
子句中的逻辑可能不是您想要的。使用IN
可以解决此问题。答案 1 :(得分:1)
尝试
SELECT account_id, date,
SUM(CASE WHEN event_type = 1 THEN count else 0 END) as shows,
SUM(CASE WHEN event_type = 4 THEN count else 0 END) as clicks
FROM widgetstatdaily
WHERE account_id = 272 AND
event_type IN (1, 4)
GROUP BY account_id, date
ORDER BY date;