SQL 计算一列中两个日期之间的天数

问题描述 投票:0回答:2

我正在尝试计算同一列中两个日期之间的天数!当 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)。

sql sql-server
2个回答
1
投票

您可以使用窗口函数

LAG()
来检索先前的行,并使用
DATEDIFF
函数来计算两个日期之间的天数差异:

SELECT *, DATEDIFF(dt, LAG(dt, 1, dt) OVER (PARTITION BY ID ORDER BY dt)) as Days 
FROM mytable;

演示在这里


0
投票

这个例子有帮助吗?

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
© www.soinside.com 2019 - 2024. All rights reserved.