【发布时间】:2016-09-07 14:17:31
【问题描述】:
我正在编写一个 SQL 查询,用于提取过去 4 周的一些信息。 我的结果有两个问题(见下文)。
第一个问题是,当我回顾 4 周时,范围应该是 8 月 10 日 - 9 月 6 日。当我按“日期”订购时,9 月的日期会移动到结果实际上应该在最后。所以我的结果应该从 10(8 月)开始,到 6(9 月)结束。
第二个问题是我错过了一些随机日期(3、4、13、27)。
Day of the Month Number of X
1 125
2 77
5 5
6 23
10 145
11 177
12 116
14 2
15 199
16 154
17 134
18 140
19 154
21 8
22 166
23 145
24 151
25 107
26 79
28 3
29 151
30 163
31 147
这里是我的查询的一般版本:
DECLARE @startDate datetime, @endDate datetime;
SET @startDate = dateadd(day, -28, GETDATE());
SET @endDate = dateadd(day, -1, GETDATE());
Select DATEPArt(dd, Time) AS 'Day of the Month', count(*) AS ' Number of X'
from SomeTable ST
where Time >= @startDate
AND Time < @endDate
group by DATEPArt(dd, Time)
order by 'Day of the Month'
【问题讨论】:
-
如果您缺少日期数据,您可能需要创建和使用日历表。
标签: sql sql-server tsql datetime sql-order-by