我试图获取每个月的数据,如果没有找到特定月份的数据,我会把它归零。我已经创建了一个日历表,所以我可以加入它,但我仍然无法获得零。
这是我的查询
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
我的日历表中的值是1-12(Jan-Dec)int
结果应该是这样的
month total
1 0
2 20
3 0
4 2
..
11 0
12 10
更新
问题似乎是SUM函数
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
我尝试只显示ID,但运行良好。但是当我加回这个功能。我只能在数月内获得价值。
COALESCE(SUM(tp.total), 0);
答案 0 :(得分:3)
这可以解决您的查询问题:
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;
这仅适用于"日历"表每月有一行 - 这看起来很奇怪,但这可能是你的数据结构。
请注意更改:
calendar
表开始,因为这些是您要保留的行。LIKE
与日期一起使用。 MySQL具有正确的date
函数。使用它们。ON
子句而不是WHERE
子句中。COALESCE()
到IFNULL()
,因为COALESCE()
是ANSI标准。答案 1 :(得分:0)
您需要根据查询使用权限,因为您的日历表位于右侧
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