我有一种奇怪的行为,如果有人能解释一下,我会很高兴吗?今天是2016年5月22日(对于未来的读者)。
SELECT `Opened`,
`Milestone_Status`,
Year(`Opened`),
Month(`Opened`),
Count(*) As Total_Rows
FROM Cases
WHERE `Opened` BETWEEN (CURRENT_DATE() - INTERVAL 6 MONTH) AND (CURRENT_DATE() - INTERVAL 2 MONTH)
GROUP BY Year(`Opened`), Month(`Opened`), `Milestone_Status`;
结果如下:
+------------+------------------+----------------+-----------------+------------+
| Opened | Milestone_Status | Year(`Opened`) | Month(`Opened`) | Total_Rows |
+------------+------------------+----------------+-----------------+------------+
| 2016-12-07 | Compliant | 2016 | 12 | 2 |
| 2017-01-10 | Compliant | 2017 | 1 | 6 |
| 2017-02-23 | Closed Violation | 2017 | 2 | 1 |
| 2017-02-27 | Compliant | 2017 | 2 | 1 |
| 2017-03-01 | Closed Violation | 2017 | 3 | 1 |
| 2017-03-06 | Compliant | 2017 | 3 | 2 |
+------------+------------------+----------------+-----------------+------------+
6 rows in set (0.02 sec)
因此,当我将一个月的差异从2更改为3时,它应该显示直到月份的行('已打开')2,但是..
SELECT `Opened`,
`Milestone_Status`,
Year(`Opened`),
Month(`Opened`),
Count(*) As Total_Rows
FROM Cases WHERE `Opened` BETWEEN (CURRENT_DATE() - INTERVAL 6 MONTH) AND (CURRENT_DATE() - INTERVAL 3 MONTH)
GROUP BY Year(`Opened`), Month(`Opened`), `Milestone_Status`;
result:
+------------+------------------+----------------+-----------------+------------+
| Opened | Milestone_Status | Year(`Opened`) | Month(`Opened`) | Total_Rows |
+------------+------------------+----------------+-----------------+------------+
| 2016-12-07 | Compliant | 2016 | 12 | 2 |
| 2017-01-10 | Compliant | 2017 | 1 | 6 |
+------------+------------------+----------------+-----------------+------------+
2 rows in set (0.01 sec)
任何想法,更好的方法,请?
答案 0 :(得分:0)
不,输出正确。正如
CURRENT_DATE() - INTERVAL 3 MONTH
是
2017年2月22日
所以你查询成为:
SELECT `Opened`,`Milestone_Status`,YEAR(`Opened`), MONTH(`Opened`),
COUNT(*) AS Total_Rows
FROM Cases WHERE `Opened`
BETWEEN (2016-11-22) AND (2017-02-22)
GROUP BY YEAR(`Opened`), MONTH(`Opened`), `Milestone_Status`;
答案 1 :(得分:0)
因此,当我将一个月的差异从2更改为3时,它应该显示直到月份('已打开')2的行,但是..
因为今天是22岁所以你的结果是真的。
如果您想从2获得月份('已打开'),请使用月份。
使用DATEADD()
编辑:CURRENT_DATEEx:3个月:DATEADD(m,-3,GETDATE())。
希望它会对你有所帮助。