我有一个带有 ID 和日期字段的表
ID |Date
1 |2013-5-22
1 |2013-5-23
1 |2013-5-25
1 |2013-5-26
2 |2013-5-26
2 |2013-5-27
1 |2013-5-27
1 |2013-5-28
使用 Row_Number 我可以按 id 对所有数据进行分组,并设置 Min date 和 Max Date
;WITH q AS(
SELECT f.*,
grp = DATEDIFF(day, 0, f.Date) - ROW_NUMBER() OVER (PARTITION BY f.ID ORDER BY f.Date),
FROM myTable f
)
SELECT
MIN(q.ID) as ID,
MIN(q.Date) as StartDate,
MAX(q.Date) as EndDate
FROM q
GROUP BY q.grp, q.ID, Date
;
结果:
ID |StartDate |EndDate
1 |2013-5-22 |2013-5-23
2 |2013-5-26 |2013-5-27
1 |2013-5-25 |2013-5-28
现在我需要按 <= 3 步获取日期示例:
ID |StartDate |EndDate
1 |2013-5-22 |2013-5-23
2 |2013-5-26 |2013-5-27
1 |2013-5-25 |2013-5-27
1 |2013-5-28 |2013-5-28
有人可以请照亮我的路吗?泰
编辑 对不起
;WITH q AS(
SELECT f.*,
grp = DATEDIFF(day, 0, f.Date) - ROW_NUMBER() OVER (PARTITION BY f.ID ORDER BY f.Date)
FROM MyTable f
)
SELECT
MIN(q.ID) as ID,
MIN(q.Date) as StartDate,
MAX(q.Date) as EndDate
FROM q
GROUP BY q.grp, q.ID
;