我已经能够选择今年的所有月份,如果它们存在,则可以选择最后一个月。我想要做的是创建一个未来的日期,如果它没有任何存在,TotalAmount为0.我可以用PHP填写这个,但我希望MYSQL有一个更简单的解决方案。
SELECT
DATE_FORMAT(STR_TO_DATE(Invoice.Date, '%m/%e/%Y'), '%m-%Y') AS Date_Month,
SUM(Invoice.Amount) AS TotalAmount
FROM Invoice
WHERE STR_TO_DATE(Invoice.Date, '%m/%e/%Y') BETWEEN DATE_SUB(DATE_ADD(DATE_SUB(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) DAY), INTERVAL 1 YEAR), INTERVAL 2 YEAR) AND NOW()
GROUP BY Date_Month
ORDER BY Date_Month
当前输出:
01-2016 | 103077
01-2017 | 104925
02-2016 | 187065
02-2017 | 32865
03-2016 | 135525
04-2016 | 106500
05-2016 | 98812
06-2016 | 111690
07-2016 | 96193
08-2016 | 123970
09-2016 | 126356
10-2016 | 147454
11-2016 | 160254
12-2016 | 98430
预期产出:
01-2016 | 103077
01-2017 | 104925
02-2016 | 187065
02-2017 | 32865
03-2016 | 135525
03-2017 | 0
04-2016 | 106500
04-2017 | 0
05-2016 | 98812
05-2017 | 0
06-2016 | 111690
06-2017 | 0
07-2016 | 96193
07-2017 | 0
08-2016 | 123970
08-2017 | 0
09-2016 | 126356
09-2017 | 0
10-2016 | 147454
10-2017 | 0
11-2016 | 160254
11-2017 | 0
12-2016 | 98430
12-2017 | 0
答案 0 :(得分:0)
您可以使用此类查询执行此操作,但未经过测试
SELECT
DATE_FORMAT(STR_TO_DATE(Invoice.Date, '%m/%e/%Y'), '%m-%Y') AS Date_Month,
SUM(IF(STR_TO_DATE(Invoice.Date > NOW(), 0, Invoice.Amount)) AS TotalAmount
FROM Invoice
WHERE STR_TO_DATE(Invoice.Date, '%m/%e/%Y') BETWEEN DATE_SUB(DATE_ADD(DATE_SUB(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) DAY), INTERVAL 1 YEAR), INTERVAL 2 YEAR) AND NOW()
GROUP BY Date_Month
ORDER BY Date_Month;