我有一個查詢從條件滿足的表中選擇列,問題是這個邏輯被重複多次(每個列需要一次),並想知道是否有更好的這樣做的方式。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 ''
你可以編寫一個函數來保存CASE邏輯,只要提供你的日期,如果它應該失控。 – Jens
@Jens我在想,但ID必須通過列作爲參數,而不是價值wouldnt我? –