首页 > 解决方案 > SQL:在更大的时间范围内的特定时间范围内计数

问题描述

我有一张如下所示的表格。每次有人发言时,都会出现一个新行,其中包含日期、发言者和每个评论唯一的评论 ID。该表有 3 年的数据。

我想做的是在 SQL 中找到一个解决方案,可以优雅地挑选过去 1 年内在 2 天内发言超过 6 次的人。

例如,从示例表中,我想看到的是:

无关紧要的是:

日期 评论编号
2021-10-20 一个 费瓦吉亚
2021-10-20 阿菲瓦斯
2021-10-20 一个 iewaokdow
2021-10-20 一个 欧维达雷克
2021-10-20 一个 斯凯德克
2021-10-19 凯雅杰斯
2021-10-19 一个 voewaikd
2021-10-19 绍韦克拉德夫
2021-10-19 一个 诗歌
2021-10-18 一个 比瓦尔德韦
2021-10-18 一个 真实的
2021-10-18 zfdewoaierje
2021-10-18 克费瓦吉勒伊夫德
2021-10-18 费艾维瑞
2021-10-18 wrfeiarjeilwaf
2021-10-18 yhfewaurhdfj

标签: sqltimecount

解决方案


看看这个:

declare @MyTable as table (
    [Date] datetime,
    Person varchar(3),
    CommentID varchar(50)
)

INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('20/10/21', 'A', 'fjeiwarjea')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('20/10/21', 'B', 'ahfeawas')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('20/10/21', 'A', 'iewaokdow')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('20/10/21', 'A', 'oweidarek')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('20/10/21', 'A', 'sqoeidke')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('19/10/21', 'B', 'qejacjes')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('19/10/21', 'A', 'voewaiekd')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('19/10/21', 'B', 'saoweikladf')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('19/10/21', 'A', 'poewieakre')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'A', 'biewaldcwe')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'A', 'deaireal')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'B', 'zfdewoaierje')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'B', 'kfewajireuifd')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'B', 'mfeaiwruei')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'B', 'wrfeiarjeilwaf')
INSERT INTO @MyTable ([Date], Person, CommentID) VALUES ('18/10/21', 'B', 'yhfewaurhdfj');

with Comments (FromDate, ToDate, Person, Times)
as
(
    select t1.[Date] FromDate, DATEADD(d, -1, t1.[date]) ToDate, t1.Person, 
    (
        select COUNT(*) from @MyTable t2 where t2.Person = t1.Person and t2.[Date] between DATEADD(d, -1, t1.[date]) and t1.[date]
    ) Times
    from @MyTable t1
    where t1.[Date] > DATEADD(yy, -1, getdate()) -- just last year
    group by t1.[Date], DATEADD(d, -1, t1.[date]), t1.Person
)
select * from Comments where Times >= 6 

这将返回:

从日期 迄今为止 时代
2021-10-19 00:00:00.000 2021-10-18 00:00:00.000 7
2021-10-20 00:00:00.000 2021-10-19 00:00:00.000 一个 6

我认为代码是自我解释的,但是如果您需要一些解释,我可以更新答案。


推荐阅读