2016-08-12 50 views
0

我有表如下圖所示,如何考慮在條件,如果一列是空的另一列

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。

回答

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

您在第二個查詢中混淆了日期。 (我懷疑SQL Server會爲該查詢使用索引,但它可能值得一試。可惜的是,SQL Server不支持函數索引,您可以簡單地將'coalesce(approved_date,created_date)'索引爲'。)。 –

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的壓力。

換句話說,在上面的查詢,如果它是不NULLApproved_Date將被使用,否則它是回退到Created_Date

相關問題