So, I am using Room in Java in Android.
I am returing the list of payment from the database like this
"SELECT IFNULL(SUM(payment), 0) FROM works_db_table WHERE account_year = :year " +
" GROUP BY account_month ORDER BY account_month
But, it returns nothing if the payment of certain month is 0. For instance, if payment for month 1 is 200, payment for month 2 is 0, and payment for month 3 is 100, it will return [200, 100], not [200, 0, 100).
I have tried with IFNULL, but happens the same.
The answer of @forpas fixed this, but his code has some errors. The code below is slightly modified version of his code-
SELECT Ifnull(Sum(w.payment), 0)
FROM (SELECT 1 month
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
UNION ALL
SELECT 11
UNION ALL
SELECT 12) m
LEFT JOIN works_db_table w
ON w.account_month = m.month
AND w.account_year = :year
GROUP BY m.month
You need a query that returns all the months 1-12 and then LEFT
join it to the table:
SELECT IFNULL(SUM(w.payment), 0)
FROM (
SELECT 1 month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
) m LEFT JOIN works_db_table w
ON w.account_month = m.month AND w.account_year = :year
GROUP BY m.month