1

刚刚意识到我的 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 为负数时,您会看到问题出现了,因为它不知道如何转到上一年。有没有更好的方法来实现这一目标?

4

2 回答 2

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

于 2013-09-29T18:21:35.010 回答
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 ;
于 2013-09-30T16:04:00.200 回答