使用MS SQL的时差查询

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

我正在尝试使用AM,PM来消除两次之间的差异,第一次和第二次之间我有专栏:

FirstTime    SecondTime
10:14:42 PM  1:05:25 AM. 

[当我使用DateDiff函数时,它返回错误的值,并且我也想在整个表中访问而不是单行,并且在特定表上需要最大值

我已经尝试过以下查询:

select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no 
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ; 

但是两者都返回错误的值。

sql sql-server tsql
1个回答
0
投票

我只是从评论中了解到,您认为-1269是错的,但没有错。

您需要反转列的顺序以获得所需的结果,因为FirstTime应该<= SecondTime。或使用ABS()函数获取正数

SELECT DATEDIFF(Minute, FirstTime, SecondTime) FirstWay,
       ABS(DATEDIFF(Minute, SecondTime, FirstTime)) SecondWay
FROM
(
    VALUES
    ('1:05:25 AM', '10:14:42 PM')
    --FirstTime should be < than SecondTime to get the desired outputs
    -- or use ABS() function to get positive number
) T(FirstTime, SecondTime)

这里是db<>fiddle

© www.soinside.com 2019 - 2024. All rights reserved.