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