2013-09-29 225 views
1

剛剛意識到我的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; 

但是你可以看到這個問題進來月份時爲負數,因爲它不知道如何去上年。有沒有更好的方法來實現這一目標?

+3

日期處理在不同的DBMS上有所不同。你在用哪個? SQLite的? MySQL的? Microsoft SQL服務器? –

+1

@CharlesBurns它有'TOP'關鍵字,所以它可能是MS SQL Server。 – RBarryYoung

回答

2

假設您正在使用SQL Server


您可以通過StatDate與第一號上年當月:) StatDate >= dateadd(month, datediff(month, 0, getdate()) - 12, 0);(和這種類型的查詢也將使用索引上StatDate列,如果您有任何)比較得到過去12個月。你也可以使用row_number()功能,讓你在一個查詢需要的數據:

with cte as ( 
    select 
     StatDate, UserCount, 
     row_number() over(partition by month(StartDate) order by StartDate desc) as rn 
    from Table1 
    where StatDate >= dateadd(month, datediff(month, 0, getdate()) - 12, 0) 
) 
select StatDate, UserCount 
from Table1 
where rn = 1 

sql fiddle demo

0

使用派生表來獲得每個月的最後日期在過去的一年,然後做一個內加入原始表格以獲得這些日期所需的計數:

SELECT UserCount, T.STATDATE 
FROM 
    (SELECT MAX(StatDate) AS STATDATE 
    FROM STATS_USERCOUNT 
    WHERE DATEDIFF(MONTH,GETDATE(),StatDate) <=12 
    GROUP BY MONTH(StatDate)) AS T 
INNER JOIN STATS_USERCOUNT S ON T.STATDATE = S.StatDate ; 
相關問題