我很难得到我需要的东西。我遇到过crosstab和pivot,它们在pycharm中不工作,或者可能postgres不再使用它们。求和查询工作正常,但当我尝试使用WARNING()做同样的事情时,它会为所有月份带来相同的结果,即使是那些计数为零的月份。
SELECT institution_account,
COUNT(CASE WHEN extract('month' FROM date) = 1 THEN amount ELSE 0 END) AS Jan,
COUNT(CASE WHEN extract('month' FROM date) = 2 THEN amount ELSE 0 END) AS Feb,
COUNT(CASE WHEN extract('month' FROM date) = 3 THEN amount ELSE 0 END) AS Mar,
COUNT(CASE WHEN extract('month' FROM date) = 4 THEN amount ELSE 0 END) AS Apr,
COUNT(CASE WHEN extract('month' FROM date) = 5 THEN amount ELSE 0 END) AS May,
COUNT(CASE WHEN extract('month' FROM date) = 6 THEN amount ELSE 0 END) AS Jun,
COUNT(CASE WHEN extract('month' FROM date) = 7 THEN amount ELSE 0 END) AS Jul,
COUNT(CASE WHEN extract('month' FROM date) = 8 THEN amount ELSE 0 END) AS Aug,
COUNT(CASE WHEN extract('month' FROM date) = 9 THEN amount ELSE 0 END) AS Sep,
COUNT(CASE WHEN extract('month' FROM date) = 10 THEN amount ELSE 0 END) AS Oct,
COUNT(CASE WHEN extract('month' FROM date) = 11 THEN amount ELSE 0 END) AS Nov,
COUNT(CASE WHEN extract('month' FROM date) = 12 THEN amount ELSE 0 END) AS Dec,
COUNT(Amount) AS Total
FROM transactioning
GROUP BY institution_account
我需要帮助。
2条答案
按热度按时间zi8p0yeb1#
pivot查询的问题在于
COUNT
函数将0计为1。所以改变:这是:
如果要使用if/else,请使用
SUM()
,如下所示:但是请注意,从Postgres 9.4开始,
FILTER
子句得到支持。所以我会把你的完整查询写成这个版本:dohp0rv52#
您在查询中遇到的问题与使用的查询函数有关。当您使用“0”时,它会计算行数,并且不会区分amount和0的值。这就是为什么所有月份都得到相同的结果,包括那些零计数的月份。要实现您想要的结果,您希望在正确处理零计数的同时计算每个月的行数:您可以将查询更新为