我有一个查询,从满足条件的表中选择列,问题是这个逻辑重复多次(每个列需要一次),并想知道是否有更好的方法。
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 :(得分:1)
不是你描述的方式......
另一种方法是使用isnull()
或coalesce()
:
select
SelectedDate = coalesce(date1,date2)
, [Day] = coalesce(day1,day2)
, [Hour] = coalesce(hour1,hour2)
, [Minute] = coalesce(minute1,minute2)
from t
答案 1 :(得分:0)
没有。每列都需要自己的select语句。
对于此CASE声明的特定应用,您可能正在使用COALESCE。
SELECT COALESCE(date1, date2) AS selectedDate FROM SomeTable