SQL连续计数天数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL连续计数天数相关的知识,希望对你有一定的参考价值。
这是SQL数据库数据:
UserTable
UserName | UserDate | UserCode
-------------------------------------------
user1 | 08-31-2014 | 232
user1 | 09-01-2014 | 232
user1 | 09-02-2014 | 0
user1 | 09-03-2014 | 121
user1 | 09-08-2014 | 122
user1 | 09-09-2014 | 0
user1 | 09-10-2014 | 144
user1 | 09-11-2014 | 166
user2 | 09-01-2014 | 177
user2 | 09-04-2014 | 188
user2 | 09-05-2014 | 199
user2 | 09-06-2014 | 0
user2 | 09-07-2014 | 155
如果[UserCode]的值不为零,则应该仅连续数天(作为结果)。UserDate介于2014年9月1日至2014年11月11日之间。仅在结果为2或更大时显示结果。
我想对我的SQL查询返回的是:
UserName | StartDate | EndDate | Result
----------------------------------------------------------
user1 | 09-01-2014 | 09-03-2014 | 2
user1 | 09-08-2014 | 09-11-2014 | 3
user2 | 09-04-2014 | 09-07-2014 | 3
仅使用SQL查询是否有可能?
答案
这是Gaps and Islands问题。解决此问题的最简单方法是使用ROW_NUMBER()
识别序列中的缺口:
SELECT UserName,
UserDate,
UserCode,
GroupingSet = DATEADD(DAY,
-ROW_NUMBER() OVER(PARTITION BY UserName
ORDER BY UserDate),
UserDate)
FROM UserTable;
这给:
UserName | UserDate | UserCode | GroupingSet
------------+---------------+------------+-------------
user1 | 09-01-2014 | 1 | 08-31-2014
user1 | 09-02-2014 | 0 | 08-31-2014
user1 | 09-03-2014 | 1 | 08-31-2014
user1 | 09-08-2014 | 1 | 09-04-2014
user1 | 09-09-2014 | 0 | 09-04-2014
user1 | 09-10-2014 | 1 | 09-04-2014
user1 | 09-11-2014 | 1 | 09-04-2014
user2 | 09-01-2014 | 1 | 08-31-2014
user2 | 09-04-2014 | 1 | 09-02-2014
user2 | 09-05-2014 | 1 | 09-02-2014
user2 | 09-06-2014 | 0 | 09-02-2014
user2 | 09-07-2014 | 1 | 09-02-2014
如您所见,这在连续行的GroupingSet
中给出了恒定值。然后,您可以按此列分组以获取所需的摘要:
WITH CTE AS
( SELECT UserName,
UserDate,
UserCode,
GroupingSet = DATEADD(DAY,
-ROW_NUMBER() OVER(PARTITION BY UserName
ORDER BY UserDate),
UserDate)
FROM UserTable
)
SELECT UserName,
StartDate = MIN(UserDate),
EndDate = MAX(UserDate),
Result = COUNT(NULLIF(UserCode, 0))
FROM CTE
GROUP BY UserName, GroupingSet
HAVING COUNT(NULLIF(UserCode, 0)) > 1
ORDER BY UserName, StartDate;
另一答案
请尝试:
;with T1 as(
select
*,
ROW_NUMBER() over ( order by UserName, UserDate) ID
from tbl
)
,T as (
SELECT *, 1 CNT FROM T1 where ID=1
union all
SELECT b.*, (case when T.UserDate+1=b.UserDate and
T.UserName=b.UserName then t.CNT
else T.CNT+1 end)
from T1 b INNER JOIN T on b.ID=T.ID+1
)
select distinct UserName, MIN(UserDate), max(UserDate)
,sum(case UserCode when 0 then 0 else 1 end) From T group by UserName, CNT
having COUNT(*)>1
以上是关于SQL连续计数天数的主要内容,如果未能解决你的问题,请参考以下文章