简体   繁体   中英

Getting all value from every month, put zero if no data of that month

i'm trying to get data for each month, if there is no data found for a particular month, I will put zero. I already created a calendar table so I can left join it, but I still can't get zero.

Here's my query

SELECT calendar.month, IFNULL(SUM(transaction_payment.total),0) AS total 
FROM `transaction` 
JOIN `transaction_payment` ON `transaction_payment`.`trans_id` = 
`transaction`.`trans_id` 
LEFT JOIN `calendar` ON MONTH(transaction.date_created) = calendar.month 
WHERE`date_created` LIKE '2017%' ESCAPE '!' 
GROUP BY calendar.month 
ORDER BY `date_created` ASC

the value in my calendar tables are 1-12(Jan-Dec) int

Result should be something like this

month   total
1       0
2       20
3       0
4       2
..
11      0
12      10

UPDATE

The problem seems to be the SUM function

SELECT c.month, COALESCE(t.trans_id, 0) AS total 
FROM calendar c
LEFT JOIN transaction t ON month(t.date_created) = c.month AND year(t.date_created) = '2018' 
LEFT JOIN transaction_payment tp ON tp.trans_id = t.trans_id 
ORDER BY c.month ASC

I tried displaying the ID only and it's running well. but when I add back this function. I can only get months with values.

COALESCE(SUM(tp.total), 0);

This fixes the issues with your query:

SELECT c.month, COALESCE(SUM(tp.total), 0) AS total 
FROM calendar c LEFT JOIN
     transaction t
     ON month(t.date_created) = month(c.month) AND
        year(t.date_created) = '2017' LEFT JOIN
     transaction_payment tp
     ON tp.trans_id = t.trans_id 
GROUP BY c.month 
ORDER BY MIN(t.date_created) ASC;

This will only work if the "calendar" table has one row per month -- that seems odd, but that might be your data structure.

Note the changes:

  • Start with the calendar table, because those are the rows you want to keep.
  • Do not use LIKE with dates. MySQL has proper date functions. Use them.
  • The filtering conditions on all but the first table should be in the ON clause rather than the WHERE clause.
  • I prefer COALESCE() to IFNULL() because COALESCE() is ANSI standard.

You need to use right as per your query because you calendar table is present at right side

SELECT calendar.month, IFNULL(SUM(transaction_payment.total),0) AS total 
FROM `transaction` 
JOIN `transaction_payment` ON `transaction_payment`.`trans_id` = 
`transaction`.`trans_id` 
RIGHT JOIN `calendar` ON MONTH(transaction.date_created) = calendar.month 
WHERE`date_created` LIKE '2017%' ESCAPE '!' 
GROUP BY calendar.month 
ORDER BY `date_created` ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM