2017-03-02 150 views
0

我有一個查詢從條件滿足的表中選擇列,問題是這個邏輯被重複多次(每個列需要一次),並想知道是否有更好的這樣做的方式。TSQL - CASE WHEN語句的多個別名

SELECT 
    CASE 
    WHEN (date1 IS NULL) THEN [date2]  
    WHEN (date1 IS NOT NULL OR (date1 IS NOT NULL AND date2 IS NOT NULL)) THEN [date1] 
    ELSE '' 
    END AS selectedDate 

//Repeat above statement for [day], [hour], [minute] 

我想知道,如果它能夠聚合與分離的別名用同一語句許多這樣的case語句,因爲它們都依賴於相同的條件,而不是多次重寫相同的語句爲每列,爲例如,我嘗試了以下內容:

SELECT 
    CASE 
    WHEN (date1 IS NULL) THEN [date2] as "selectedDate", [day2] as "day", [hour2] as "hour", [minute2] as "minute" 
    WHEN (date1 IS NOT NULL OR (date1 IS NOT NULL AND date2 IS NOT NULL)) THEN [date1] as "selectedDate", [day1] as "day", [hour1] as "hour", [minute1] as "minute" 
    ELSE '' 
+0

你可以編寫一個函數來保存CASE邏輯,只要提供你的日期,如果它應該失控。 – Jens

+0

@Jens我在想,但ID必須通過列作爲參數,而不是價值wouldnt我? –

回答

1

不要在你所描述的方式......

另一種方法是使用isnull()coalesce()

select 
    SelectedDate = coalesce(date1,date2) 
    , [Day]  = coalesce(day1,day2) 
    , [Hour]  = coalesce(hour1,hour2) 
    , [Minute]  = coalesce(minute1,minute2) 
from t 
0

不需要。每列都需要自己的select語句。

對於您的CASE聲明的特定應用,您可以改爲使用COALESCE

SELECT COALESCE(date1, date2) AS selectedDate FROM SomeTable