1

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

   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 天的记录。

4

1 回答 1

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 小提琴演示

于 2013-06-20T04:43:41.750 回答