我有一个带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分组所有数据,并按最小日期和最大日期
进行分组;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
有人可以照亮我的路吗? TY
修改 遗憾
;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
;
答案 0 :(得分: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