使用mssql的sqlserver时差查询

vof42yt1  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(246)

我试着用am,pm来区分两次,第一次和第二次,我有很多列:

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

当我使用datediff函数时,它返回错误的值,并且我希望在整个表中访问它,而不是在单行中,并且在特定表中需要max
我尝试了以下查询:

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  ;

但两者都返回错误的值。

kcwpcxri

kcwpcxri1#

我只是从你的评论中了解到 -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)

这是一把小提琴

xmd2e60i

xmd2e60i2#

你可以使用 CASE 表达式以反转 DATEDIFF 当第二次在第一次之前时的表达式。当第二次是第二天时,这将提供预期的结果。

SELECT
    CASE WHEN first_time < second_time 
        THEN DATEDIFF(MINUTE, first_time, second_time)
    ELSE
        DATEDIFF(MINUTE, second_time, first_time)
    END AS Duration
FROM tbl_weight;
t1qtbnec

t1qtbnec3#

你可以用 case 表达式:

select case when convert(datetime, firsttime) < convert(datetime, secondtime) 
            then dateadd(second, datediff(second, secondtime, firsttime), 0)
            else dateadd(second, datediff(second, firsttime, secondtime), 0)
       end

相关问题