我似乎无法让我的GROUP BY正确处理日期。目前它仍在分组,好像我在DATE_FORMAT中使用'%m /%e /%Y'。
SELECT
DATE_FORMAT(STR_TO_DATE(Invoice.Date, '%m/%e/%Y'), '%m-%Y') AS Date,
SUM(Invoice.Amount) AS TotalAmount
FROM Invoice
WHERE STR_TO_DATE(Invoice.Date, '%m/%e/%Y') BETWEEN DATE_SUB(NOW(), INTERVAL 2 YEAR) AND NOW()
GROUP BY Date
ORDER BY Date
当前输出(如您所见,它显示每个月的倍数,因为它仍然会看到%e部分):
01-2016 | 24017
01-2016 | 28886
01-2016 | 0
01-2016 | 31653
01-2016 | 18521
01-2017 | 29409
01-2017 | 23370
01-2017 | 37611
01-2017 | 14535
02-2016 | 16365
02-2016 | 27930
预期产出:
01-2016 | 103077
01-2017 | 123446
02-2016 | 44295
答案 0 :(得分:0)
你在group by
中使用相同的表达式:
SELECT
DATE_FORMAT(STR_TO_DATE(Invoice.Date, '%m/%e/%Y'), '%m-%Y') AS Date,
SUM(Invoice.Amount) AS TotalAmount
FROM Invoice
WHERE STR_TO_DATE(Invoice.Date, '%m/%e/%Y') BETWEEN DATE_SUB(NOW(), INTERVAL 2 YEAR) AND NOW()
GROUP BY DATE_FORMAT(STR_TO_DATE(Invoice.Date, '%m/%e/%Y'), '%m-%Y')
ORDER BY Date
答案 1 :(得分:0)
问题是您的查询中名称Date
不明确。最好为列别名使用唯一的描述性名称,这样它们就不会与现有的列名冲突。
如果您将列别名更改为date_month
,那么您的查询应该按预期工作:
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(NOW(), INTERVAL 2 YEAR) AND NOW()
GROUP BY date_month
ORDER BY date_month