也许有一个简单的修复,但我无法解决问题。我会尽力解释我的情况。
我正在处理MySQL查询,该查询将在日期范围内(在A列中)返回结果,并在日期范围内返回1年(在B列中)。我需要按月份而不是按年份对结果进行分组。所以我想有这样的事情:
2014 2013 ---------------- 01-01 6 8 01-03 7 0 01-04 4 1 01-08 0 13 01-21 11 7
在我当前的查询(下面)中,我得到这样的结果(因为CASE中的ELSE):
2014 2013 ---------------- 01-01 0 8 01-03 7 0 01-04 0 1 01-08 0 13 01-21 0 7
QUERY:
SELECT
DATE_FORMAT(table.date, '%e.%c.') AS date,
(CASE WHEN DATE(table.date) BETWEEN '2014-01-01' AND '2014-02-01' THEN ROUND(SUM(table.field), 2) ELSE 0 END) AS field_2014,
(CASE WHEN DATE(table.date) BETWEEN '2013-01-01' AND '2013-02-01' THEN ROUND(SUM(table.field), 2) ELSE 0 END) AS field_2013
FROM table
WHERE
(DATE(table.date) BETWEEN '2014-05-01' AND '2014-06-01' OR DATE(table.date) BETWEEN '2013-05-01' AND '2013-06-01')
GROUP BY
DATE_FORMAT(table.date, '%c.%e.')
我应该在ELSE中放置什么以及如何实现此功能?
感谢您的时间
答案 0 :(得分:1)
您需要聚合功能。我建议:
SELECT DATE_FORMAT(t.date, '%e.%c.') AS date,
SUM(CASE WHEN year(t.date) = 2014 THEN ROUND(SUM(t.field), 2) ELSE 0 END) AS field_2014,
SUM(CASE WHEN year(t.date) = 2013 THEN ROUND(SUM(t.field), 2) ELSE 0 END) AS field_2013
FROM table t
WHERE year(t.date) in (2013, 2014) and month(t.date) = 5
GROUP BY DATE_FORMAT(t.date, '%c.%e.');
我还建议使用格式'%m-%d'
。拥有当年的月份意味着order by
将对该列起作用。让所有日期宽度相同(" 05/01"而不是" 5/1")更好地对应于您想要的输出。