我如何按天分组但在SQL Server 2008中过去5天计数

时间:2013-06-20 04:34:00

标签: sql-server-2008 count group-by

给定一个带有日期列的表,其中包含

等数据
   2013-06-07 19:23:04.000
   2013-06-07 19:23:04.000
   2013-06-06 06:47:18.000
   2013-06-06 06:47:17.000
   2013-06-05 01:04:06.000
   2013-06-05 01:04:06.000
   2013-06-04 17:08:11.000
   2013-06-04 17:08:11.000
   2013-06-02 14:50:15.000
   2013-06-02 14:50:15.000
   2013-05-29 15:04:06.000
   2013-05-29 15:04:06.000

我想写一个每天返回一行的查询,并计算当天和之前3天的所有记录。

像这样

2013-06-07 - 8
2013-06-06 - 6
2013-06-05 - 6
2013-06-04 - 4
2013-06-02 - 2
2013-05-29 - 2

按日计算的简单组和计数(*)不起作用,因为它仅计算每天不是每天和之前3天的记录。

1 个答案:

答案 0 :(得分:1)

这样的东西
DECLARE @Table TABLE(
        Val DATETIME
)

INSERT INTO @Table SELECT '2013-06-07 19:23:04.000'
INSERT INTO @Table SELECT '2013-06-07 19:23:04.000'
INSERT INTO @Table SELECT '2013-06-06 06:47:18.000'
INSERT INTO @Table SELECT '2013-06-06 06:47:17.000'
INSERT INTO @Table SELECT '2013-06-05 01:04:06.000'
INSERT INTO @Table SELECT '2013-06-05 01:04:06.000'
INSERT INTO @Table SELECT '2013-06-04 17:08:11.000'
INSERT INTO @Table SELECT '2013-06-04 17:08:11.000'
INSERT INTO @Table SELECT '2013-06-02 14:50:15.000'
INSERT INTO @Table SELECT '2013-06-02 14:50:15.000'
INSERT INTO @Table SELECT '2013-05-29 15:04:06.000'
INSERT INTO @Table SELECT '2013-05-29 15:04:06.000'

;WITH Vals AS (
        SELECT  CAST(Val AS DATE) ValDateOnly
        FROm    @Table
)

SELECT distinct ValDateOnly,
        (SELECT COUNT(1) FROM Vals WHERE ValDateOnly BETWEEN DATEADD(day,-3,v.ValDateOnly) AND v.ValDateOnly) Cnt
FROM    Vals v

SQL Fiddle DEMO