Datediff()天重叠?

时间:2015-10-11 11:45:13

标签: sql-server time sql-server-2012 overlap datediff

我无法弄清楚如何使用datediff()函数来重叠。

这是我的桌子和黄色标记的行我遇到了麻烦。

SELECT 
    FOMTID,
    TOMTID,
    DATEDIFF(MINUTE, FOMTID,TOMTID) TIME 
FROM [DATABASE]...

enter image description here

有像'2001-01-01 23:30'这样的字段。 '2001-01-02 00:00'这会使日期差异功能起作用,但我只有时间。

2 个答案:

答案 0 :(得分:1)

如果这些是时间数据类型:

SELECT FOMTID, TOMTID,
       (CASE WHEN FOMTID <= TOMTID THEN DATEDIFF(MINUTE, FOMTID, TOMTID)
             ELSE 24*60 - DATEDIFF(MINUTE, TOMTID, FOMTID)
        END) AS TIME 

Here是一个小小的SQL小提琴。

答案 1 :(得分:1)

<强> LiveDemo

SELECT 
  FOMTID,
  TOMTID, 
  [TIME] = IIF(FOMTID <= TOMTID,
              DATEDIFF(MINUTE, FOMTID,TOMTID),
              1440 - DATEDIFF(MINUTE, TOMTID,FOMTID))
FROM your_table;

或:

SELECT 
  FOMTID,
  TOMTID, 
  [TIME] = IIF(FOMTID <= TOMTID,
                     DATEDIFF(MINUTE, FOMTID,TOMTID),
              1440 + DATEDIFF(MINUTE, FOMTID,TOMTID))
FROM your_table;

修改

<强> LiveDemo2

WITH cte AS
(
SELECT 
  FOMTID,
  TOMTID, 
  [TIME] = IIF(FOMTID <= TOMTID,
                     DATEDIFF(MINUTE, FOMTID,TOMTID),
              1440 + DATEDIFF(MINUTE, FOMTID,TOMTID))
FROM #tab
)
SELECT FOMTID, TOMTID
   ,[MINUTES] = [TIME]
   ,[TIME]  = CAST([TIME] / 60  + [TIME] % 60 / 100.0 AS DECIMAL(8,2))
   ,[TIME2] = CAST([TIME] / 60  + [TIME] % 60 / 60.0 AS DECIMAL(8,2))
FROM cte

选择您希望如何处理分钟部分:

[Time]  => 30min => 0.3
[Time2] => 30min => 0.5