使用if语句选择SQL

时间:2016-08-01 01:54:06

标签: sql sql-server

我想选择何时或如果声明

select 
    ID, name,Departmen, date, clock_in, clock_out,
    DATEDIFF(MINUTE, on_duty, clock_in) as late,
    DATEDIFF(MINUTE, off_duty, clock_out) as Early,
    DATEDIFF(MINUTE, on_duty, clock_in) - DATEDIFF(MINUTE, off_duty, clock_out) as total_telat when late <=30 from kkpsurabaya

我希望make total_telat只计算1-30分钟

3 个答案:

答案 0 :(得分:1)

使用CASE . . WHEN . . END

select  ID, 
    name,
    Departmen, date, clock_in, clock_out,
    DATEDIFF(MINUTE, on_duty, clock_in ) as late  ,
    DATEDIFF(MINUTE, off_duty, clock_out ) as Early,
    CASE 
    WHEN DATEDIFF(MINUTE, on_duty, clock_in ) < 30
    THEN DATEDIFF(MINUTE,on_duty, clock_in ) - DATEDIFF(MINUTE ,off_duty, clock_out ) 
    END as total_telat
from    kkpsurabaya

答案 1 :(得分:0)

Case语句最接近if并通过所有版本支持。这只是您理解的一个例子。我希望研究案例可以帮助你实现你所需要的。

SELECT CAST(
             CASE 
                  WHEN  (DATEDIFF(MINUTE,on_duty, clock_in ) - DATEDIFF(MINUTE ,off_duty, clock_out ))> '0' or (DATEDIFF(MINUTE,on_duty, clock_in ) - DATEDIFF(MINUTE ,off_duty, clock_out )) < '31' 
                     THEN 1 
                  ELSE 0 
             END AS bit) as Saleable, * 
FROM Product

答案 2 :(得分:0)

  SELECT ID
        ,NAME
        ,Departmen
        ,DATE
        ,clock_in
        ,clock_out
        ,DATEDIFF(MINUTE, on_duty, clock_in) AS late
        ,DATEDIFF(MINUTE, off_duty, clock_out) AS Early
        ,total_telat = iif(DATEDIFF(MINUTE, on_duty, clock_in)<= 30, DATEDIFF(MINUTE, on_duty, clock_in) - DATEDIFF(MINUTE, off_duty, clock_out), NULL)
    FROM kkpsurabaya