IIF与ISNULL?

时间:2018-07-24 07:46:27

标签: sql sql-server tsql

    SELECT first_name, last_name
    (SELECT  ISNULL(IIF(getdate() between vacation_start and vacation_end, 1, 0),0) from vacatoin_request where mat_emp = W.mat_emp) as is_on_vacation,
    (SELECT  ISNULL(IIF(getdate() between mission_start and mission_end, 1, 0),0) from mission_order where mat_emp = W.mat_emp) as is_on_mission
    FROM
    workers W

IIF运行正常,但是当我添加ISNULL时,如果该工作人员在其他表中没有休假请求或任务订单,则它仍返回null。

3 个答案:

答案 0 :(得分:1)

问题在于select返回NULL,因此ISNULL必须在select之外

 SELECT first_name, last_name
    ISNULL((SELECT TOP 1 IIF(getdate() between vacation_start and vacation_end, 1, 0) from vacatoin_request where mat_emp = W.mat_emp),0) as is_on_vacation,
    ISNULL((SELECT TOP 1 IIF(getdate() between mission_start and mission_end, 1, 0) from mission_order where mat_emp = W.mat_emp),0) as is_on_mission
FROM
workers W

答案 1 :(得分:0)

SELECT 
    first_name, last_name
    CASE WHEN v.mat_emp IS NOT NULL THEN 1 ELSE 0 END   as is_on_vacation
    CASE WHEN m.mat_emp IS NOT NULL THEN 1 ELSE 0 END   as is_on_mission
FROM
    workers         W   
LEFT JOIN 
    vacatoin_request    v
ON 
    v.mat_emp = W.mat_emp       AND
    getdate() between v.vacation_start and v.vacation_end
LEFT JOIN 
    mission_order       m   
ON
    m.mat_emp = W.mat_emp       AND
    getdate() between m.mission_start and m.mission_end

答案 2 :(得分:0)

SELECT first_name, last_name
    (SELECT COUNT(DISTINCT v.mat_empt) from vacatoin_request v where v.mat_emp = W.mat_emp and getdate() between vacation_start and vacation_end) as is_on_vacation,
    (SELECT COUNT(DISTINCT m.mat_emp) from mission_order m where m.mat_emp = W.mat_emp and getdate() between mission_start and mission_end) as is_on_mission
    FROM
    workers W