2017-05-22 99 views
0

我有一個奇怪的行爲,如果有人能解釋這一點,我會很高興嗎?今天是2016年5月22日(面向未來的讀者)。MySQL:BETWEEN - 查詢中的不同結果

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

well * 2017 ???? –

+0

CURRENT_DATE() - INTERVAL 6 MONTH == 2016-11-22和CURRENT_DATE() - INTERVAL 3 MONTH == 2017-02-22,所以一切正常與您的查詢:) – Jovana

回答

0

所以,當我改變從2到一個月的區別3,它應該顯示直到Month('Opened')2的行,但是..

因爲今天是22,所以你的結果是真的。

如果您想從2開始獲得Month('Opened'),請在月份試用。

編輯:CURRENT_DATE與DATEADD()

實施例:3月份:DATEADD(米,-3,GETDATE())。

希望它能幫助你。

+0

感謝您的改進。 – Slarti42

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`; 
+0

OMG - 謝謝 - pfff noob錯誤。 – Slarti42