我想计算两个不同表格中两个datetime
列的差异
值类似于2013-10-18 13:09:52.630
我确实喜欢select(a-b)
,但它没有返回确切的值。我想根据以上值计算天数。请提出一些建议
答案 0 :(得分:1)
您可以使用:
SELECT DATEDIFF(DAY, '2013-10-18 13:09:52.630', '2013-10-21 17:02:52.630')
为这些日期返回3。
如果第一个日期早于第二个日期,则会返回负值(例如-2天),您可以将DATEDIFF
包裹在ABS()
中以使值始终为正。< / p>
从2个表中获取值:
SELECT DATEDIFF(DAY, t1.Date, t2.Date) As DaysBetween
,ABS(DATEDIFF(DAY, t1.Date, t2.Date)) As DaysBetweenAlwaysPositive
FROM t1
INNER JOIN t2 ON t1.Id = t2.Id
关于评论:
SELECT
CAST(DiffMins / (60*24) AS VARCHAR) + 'days, '
+ CAST((DiffMins%(60*24))/60 AS VARCHAR) + 'hrs, '
+ CAST((DiffMins%(60*24))%60 AS VARCHAR) + 'mins ' AS dayhourmin
FROM (
SELECT DATEDIFF(MINUTE, '2013-10-18 13:09:52.630', '2013-10-19 15:12:52.630') AS DiffMins
) a
输出:1days, 2hrs, 3mins
这一切都变得非常混乱,但你可以在2表查询中使用它,如下所示:
SELECT CAST(DATEDIFF(DAY, t1.Date, t2.Date)/(60*24) AS VARCHAR) + 'days, '
+ CAST((DATEDIFF(DAY, t1.Date, t2.Date)%(60*24))/60 AS VARCHAR) + 'hrs, '
+ CAST((DATEDIFF(DAY, t1.Date, t2.Date)%(60*24))%60 AS VARCHAR) + 'mins ' AS dayhourmin
FROM t1
INNER JOIN t2 ON t1.Id = t2.Id
这是一个更大的问题,你原来的问题,所以你可能想要发布一个新的,如果这不符合你的需要。
答案 1 :(得分:-1)
SELECT TIMEDIFF('2009-05-18 15:45:57.005678','2009-05-18 13:40:50.005670');
它适用于mysql。我不知道sql server 2008