I am having difficulty in attaining what I need. I have come across crosstab and pivot of which are not working in pycharm or maybe postgres no longer uses them. The query for summing works fine but when I try doing the same with COUNT() it instead brings same result for all months, even those with zero counts.
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
I need some help here, urgently. Thanks
2
Answers
The problem with your pivot query is that the
COUNT
functions counts 0 as 1. So change:to this:
If you want to use if/else then use
SUM()
as follows:But note that from Postgres 9.4, the
FILTER
clause is supported. So I would write your full query as this version:The issue you’re encountering with your query is related to the use of the COUNT function. When you use COUNT, it counts the number of rows, and it does not distinguish between the values of amount and 0. This is why you’re getting the same result for all months, including those with zero counts.
To achieve your desired result, where you want to count the number of rows for each month while handling the zero counts correctly: you can update the query to