gpt4 book ai didi

SQL计算连续天数

转载 作者:行者123 更新时间:2023-12-02 17:03:53 25 4
gpt4 key购买 nike

这是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] 不为零,则应仅计算连续天数(作为结果)。用户日期介于 09-01-2014 和 09-11-2014 之间。仅当结果为 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;

<强> Example on SQL Fiddle

关于SQL计算连续天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com