刚刚意识到我的SQL命令无法正常工作。
基本上我有一个有两列的表。它记录每个月的用户数。 布局是这样的:
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;
但是,当MONTH为负数时,您可以看到问题出现,因为它不知道如何去往前一年。有没有更好的方法来实现这个目标?
答案 0 :(得分:2)
假设您正在使用SQL Server 。
您可以通过将StatDate与上一年当前月份的第一个数字进行比较来获得过去12个月:) StatDate >= dateadd(month, datediff(month, 0, getdate()) - 12, 0);
(如果您有任何问题,此类查询也将使用StatDate列上的索引)。您可以使用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 强>
答案 1 :(得分: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 ;