使用ID计算DATEDIFF

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

我是SQL的初学者,所以其他线程并没有真正帮助我。

我的数据库中有一个名为“任务”的表,其中存储了发生的每个任务的ID和日期。我想做的是计算每次输入之间的天数,并将其显示在另一栏中。

我发现最好将DATEDIFF函数用于此目的。

id,name,campaign_id,real_date,hist_date,mission_status
1,"The Fall of France I",2,2013-12-08,"1940-05-11 11:00:00",2
2,"The Fall of France II",2,2013-12-15,"1940-05-15 15:30:00",2
3,"The Fall of France III",2,2013-12-22,"1940-05-21 15:30:00",2
4,"The Fall of France IV",2,2014-01-05,"1940-05-24 05:30:00",2
5,"The Fall of France V",2,2014-01-12,"1940-06-01 05:30:00",2
6,"The Fall of France VI",2,2014-01-19,"1940-06-12 13:10:00",2

我希望表格在第1列中列出任务的ID,在第2列中列出hist_date,并在第3列中以天为单位列出每个日期条目之间的差额。例如

 id,hist_date,diff
    1,"1940-05-11 11:00:00",0
    2,"1940-05-15 15:30:00",4
sql sql-server datediff
1个回答
0
投票

您可以使用DATEDIFF和像这样的自连接来完成它:

SELECT a.id, a.[hist_date], ISNULL(DATEDIFF(day, b.[hist_date], a.[hist_date]),0) as [diff] 
FROM mission a
LEFT JOIN mission b ON b.id = a.id - 1

结果

id  hist_date  diff
1   1940-05-11 11:00:00.000 0
2   1940-05-15 15:30:00.000 4
© www.soinside.com 2019 - 2024. All rights reserved.