我正在尝试计算同一列中两个日期之间的天数!当 ID 相同时。
下面是一个示例...
ID Date
a 01/12/2024
a 01/13/2024
b 01/12/2024
b 01/20/2024
b 01/25/2024
c 01/12/2024
c 01/12/2024
计数天数应出现在新列中。
ID Date Days
a 01/12/2024 0
a 01/13/2024 1
b 01/12/2024 0
b 01/20/2024 8
b 01/25/2024 5
c 01/12/2024 0
c 01/12/2024 0
非常感谢任何帮助(y)。
这个例子有帮助吗?
create table #temp(
id varchar(10) null,
theDate datetime null
)
go
insert into #temp (id, theDate) values ('a','20240112')
insert into #temp (id, theDate) values ('a','20240113')
insert into #temp (id, theDate) values ('b','20240112')
insert into #temp (id, theDate) values ('b','20240120')
insert into #temp (id, theDate) values ('b','20240125')
insert into #temp (id, theDate) values ('c','20240112')
insert into #temp (id, theDate) values ('c','20240112')
select d.id, d.theDate, case when case when DATEDIFF(day,LAG(d.theDate) over (order by d.id, d.theDate),d.theDate) < 0 then 0 else DATEDIFF(day,LAG(d.theDate) over (order by d.id, d.theDate),d.theDate) end is null then '' else case when DATEDIFF(day,LAG(d.theDate) over (order by d.id, d.theDate),d.theDate) < 0 then 0 else DATEDIFF(day,LAG(d.theDate) over (order by d.id, d.theDate),d.theDate) end end Days
from #temp d
id theDate Days
a 2024-01-12 00:00:00.000 0
a 2024-01-13 00:00:00.000 1
b 2024-01-12 00:00:00.000 0
b 2024-01-20 00:00:00.000 8
b 2024-01-25 00:00:00.000 5
c 2024-01-12 00:00:00.000 0
c 2024-01-12 00:00:00.000 0