DATEDIFF没有提供正确的天数

时间:2019-02-13 19:08:06

标签: sql sql-server

我想看看这几天有2个日期之间的差异

select DATEDIFF(DAY, BuildCMPLTDT, ValidCMPLTDT) AS DateDiff  from TrackerTest where TicketID='123456'

2018-12-19 14:31:15.803BuildCMPLTDT,而2019-01-22 15:40:35.533ValidCMPLTDT的日期

这是我得到的结果:43485。但是,实际上应该是33天左右!

编辑: 所以,我有一排是这样的:

BuildCMPLTDT               ValidCMPLTDT
2018-12-19 14:31:15.803    1900-01-01 00:00:00.000

第二行是这样的:

1900-01-01 00:00:00.000    2019-01-22 15:40:35.533

现在,我想要第一个BuildCMPLTDT和第二个2018-12-19 14:31:15.803ValidCMPLTDT)之间的datediff。

3 个答案:

答案 0 :(得分:1)

运行此SQL并发布结果,

select BuildCMPLTDT, isdate(BuildCMPLTDT),
       ValidCMPLTDT, isdate(ValidCMPLTDT),
       DATEDIFF(DAY, BuildCMPLTDT, ValidCMPLTDT) AS DateDiff
from TrackerTest 
where TicketID='123456'

更新,因为他需要两个记录中的datadiff()

select DATEDIFF(DAY, max(BuildCMPLTDT), max(ValidCMPLTDT)) AS DateDiff
from TrackerTest 
where TicketID='123456'

答案 1 :(得分:1)

您要减去的日期在不同的行中
并且两行都具有相同的dim i as long with sheet1 for i=.cells(.rows.count, 1) to 2 step -1 if .cells(i, 1)=.cells(i-1, 1) then .cells(i-1, 5).resize(1, 2) = .cells(i, 3).resize(1, 2) .cells(i, 3).entirerow.delete end if next i end with ,对吗?
做您需要的最简单的方法是:

TicketID = '123456'

请参见demo

答案 2 :(得分:0)

使用lead()分析函数

with cte as
(
select '2018-12-19 14:31:15.803' as BuildCMPLTDT,'1900-01-01 00:00:00.000' as ValidCMPLTDT
union all
select '1900-01-01 00:00:00.000 ' as BuildCMPLTDT,'2019-01-22 15:40:35.533' as ValidCMPLTDT

) select DATEDIFF(day,BuildCMPLTDT,lead(ValidCMPLTDT) over(order by ValidCMPLTDT))  from cte

Demo link