剛剛意識到我的SQL命令無法正常工作。SQL獲取過去12個月的數據
基本上我有一個兩列的表。它跟蹤每個月的用戶數量。 佈局如下:
StatDate UserCount
-------- ---------
11/2/2012 5
12/8/2012 10
12/23/2012 25
1/8/2013 50
2/18/2013 100
3/22/2013 33
等等。你可以看到每個月可以有多個條目。我需要能夠檢索過去一年中每個月的最新值,以便我可以將它放在線圖中。
我這樣做:
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 0 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 1 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 2 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 3 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 4 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 5 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 6 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 7 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 8 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 9 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 10 ORDER BY StatDate DESC;
SELECT TOP 1 UserCount FROM Stats_UserCount WHERE MONTH(StatDate)=MONTH(GetDate()) - 11 ORDER BY StatDate DESC;
但是你可以看到這個問題進來月份時爲負數,因爲它不知道如何去上年。有沒有更好的方法來實現這一目標?
日期處理在不同的DBMS上有所不同。你在用哪個? SQLite的? MySQL的? Microsoft SQL服務器? –
@CharlesBurns它有'TOP'關鍵字,所以它可能是MS SQL Server。 – RBarryYoung