1

我有一个带有 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
;
4

1 回答 1

0

我的第一次尝试有一个错误,试试这个:

;WITH q AS(
  SELECT ID, Date,
  grp = DATEDIFF(day, 0, Date) - ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date)
FROM  myTable
), r as
(
  select id, date, grp, 
  (ROW_NUMBER() OVER (PARTITION BY grp ORDER BY Date)-1)/3 a from q
)
SELECT 
MIN(ID) as ID,
MIN(Date) as StartDate,
MAX(Date) as EndDate
FROM r
GROUP BY grp, ID, a
于 2013-05-22T14:39:12.220 回答