如果一列为null,如何考虑where条件中的另一列

时间:2016-08-12 09:34:47

标签: sql-server

我有如下表格,

Order_id      Created_Date       Approved_Date
_______________________________________________
1              2016-08-01         2016-08-05
2              2016-07-01         2016-07-04
3              2016-06-01         NULL


Select * from table1 where Approved_date between '2016-05-01' and '2016-08-31'

如果Approved_date为NULL,则应动态考虑Created_date。

2 个答案:

答案 0 :(得分:1)

Select * from table1 
where coalesce(Approved_date, Created_Date) between '2016-05-01' and '2016-08-31'

或继续使用索引

Select * from table1 
where 
(
   Approved_date is not null 
   and Approved_date between '2016-05-01' and  '2016-08-31'
)
or 
(
   Approved_date is null 
   and Created_Date between '2016-05-01' and  '2016-08-31'
)

答案 1 :(得分:0)

使用COALESCE

SELECT t1.Order_id,
       t1.Created_Date,
       COALESCE(t1.Approved_Date, t1.Created_Date)
FROM table1 t1
WHERE Approved_date BETWEEN '2016-05-01' AND '2016-08-31'

来自documentation

  

按顺序计算参数,并返回最初未计算为NULL的第一个表达式的当前值。

换句话说,如果上述查询Approved_Date不是NULL,则会使用Created_Date,否则会回退到Sub stackfun() Set olApp = CreateObject("Outlook.application") Set objMail = olApp.CreateItem(olMailItem) With objMail .Display .To = "tomisgreat@something.com" .Subject = "you rule" 'HTML for fun .BodyFormat = olFormatHTML .HTMLBody = "<HTML><H2>Y HELO THAR</BODY></HTML>" .DeferredDeliveryTime (#11:59:59 PM#) End With End Sub