具有表条件的Where子句

时间:2014-08-21 19:00:52

标签: sql

我想写一个查询,根据卡车的状态“filter”返回行数。如果我只希望看到未关闭的卡车,‘1’可以看到所有卡车,我会从UI发送‘2’的值。

select *
from invoice left outer
join truck
     on (invoice.invnum = truck.invnum)

返回正确的行数。

问题: 我需要一个where子句来查看卡车表的close_date字段并确定它是否为空。如果在卡车表中没有找到记录,仍然会从发票表中返回该行。

select *
from invoice left outer
join truck
     on (invoice.invnum = truck.invnum)
where UI.value = (select close_date from truck where invoice.invnum = truck.invnum) “if no record is returned here, return the value ‘2’

1 个答案:

答案 0 :(得分:0)

请澄清你的问题。你想做这样的事吗?

select *
from 
    invoice 
     left outer join 
    truck on 
        invoice.invnum = truck.invnum
where 
    (UI.value = 1 AND truck.close_date IS NULL) OR
    (UI.value = 2)

或者你想要这样做吗?

select *
from 
    invoice 
     left outer join 
    truck on 
        invoice.invnum = truck.invnum
where UI.Value = 
  (
    SELECT CASE WHEN MAX(close_date) IS NULL THEN 2 ELSE 1 END 
    FROM truck 
    WHERE invoice.invnum = truck.invnum)