KCh*_*han 5 sql sql-server loops while-loop
我有一个看起来像这样的记录子集:
ID DATE
A 2015-09-01
A 2015-10-03
A 2015-10-10
B 2015-09-01
B 2015-09-10
B 2015-10-03
...
Run Code Online (Sandbox Code Playgroud)
对于每个ID,第一个最小日期是第一个索引记录.现在我需要在索引记录的30天内排除案例,并且任何日期大于30天的记录将成为另一个索引记录.
例如,对于ID A,2015-09-01和2015-10-03都是索引记录,并且将保留,因为它们相隔超过30天.2015-10-10将被删除,因为它是在第二个索引案例的30天内.
对于ID B,2015-09-10将被删除,并且不会成为索引案例,因为它在第一个索引记录的30天内.2015-10-03将保留,因为它超过第一个指数记录的30天,并将被视为第二个指数案例.
输出应如下所示:
ID DATE
A 2015-09-01
A 2015-10-03
B 2015-09-01
B 2015-10-03
Run Code Online (Sandbox Code Playgroud)
我如何在SQL Server 2012中执行此操作?ID可以拥有的日期数量没有限制,可以是1到5或更多.我对SQL非常基础,所以任何帮助都会非常感激.
小智 2
就像在您的示例中一样,#test 是包含数据的表:
;with cte1
as
(
select
ID, Date,
row_number()over(partition by ID order by Date) groupID
from #test
),
cte2
as
(
select ID, Date, Date as DateTmp, groupID, 1 as getRow from cte1 where groupID=1
union all
select
c1.ID,
c1.Date,
case when datediff(Day, c2.DateTmp, c1.Date) > 30 then c1.Date else c2.DateTmp end as DateTmp,
c1.groupID,
case when datediff(Day, c2.DateTmp, c1.Date) > 30 then 1 else 0 end as getRow
from cte1 c1
inner join cte2 c2 on c2.groupID+1=c1.groupID and c2.ID=c1.ID
)
select ID, Date from cte2 where getRow=1 order by ID, Date
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |