我正在编写一个SQL查询,其中返回的一些列需要根据很多条件进行计算。
我目前正在使用嵌套的case语句,但它变得凌乱。是否有更好的(更有组织和/或可读)的方式?
(我使用的是Microsoft SQL Server,2005)
简化示例:
SELECT
col1,
col2,
col3,
CASE
WHEN condition
THEN
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation1
ELSE calculation2
END
ELSE
CASE
WHEN condition2
THEN calculation3
ELSE calculation4
END
END
ELSE
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation5
ELSE calculation6
END
ELSE
CASE
WHEN condition2
THEN calculation7
ELSE calculation8
END
END
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
答案 0 :(得分:166)
您可以尝试某种COALESCE技巧,例如:
SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... )
答案 1 :(得分:80)
将所有这些案件包装成一个。
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
ELSE NULL
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
答案 2 :(得分:25)
您可以结合多个条件来避免这种情况:
CASE WHEN condition1 = true AND condition2 = true THEN calculation1
WHEN condition1 = true AND condition2 = false
ELSE 'what so ever' END,
答案 3 :(得分:16)
我个人这样做,保持嵌入式CASE表达式的限制。我还会发表评论来解释发生了什么。如果它过于复杂,请将其分解为功能。
SELECT
col1,
col2,
col3,
CASE WHEN condition THEN
CASE WHEN condition1 THEN
CASE WHEN condition2 THEN calculation1
ELSE calculation2 END
ELSE
CASE WHEN condition2 THEN calculation3
ELSE calculation4 END
END
ELSE CASE WHEN condition1 THEN
CASE WHEN condition2 THEN calculation5
ELSE calculation6 END
ELSE CASE WHEN condition2 THEN calculation7
ELSE calculation8 END
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
答案 4 :(得分:9)
这是嵌套的“Complex”case语句的简单解决方案: - 嵌套案例复杂表达
select datediff(dd,Invdate,'2009/01/31')+1 as DaysOld,
case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else
case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else
case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else
case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end
end
end
end
end
end as Bucket
from rm20090131atb
确保每个案例陈述都有一个结束语句
答案 5 :(得分:5)
用户定义的函数可以更好地服务,至少隐藏逻辑 - 尤其是。如果你需要在多个查询中执行此操作
答案 6 :(得分:5)
我们可以将多个条件组合在一起以降低性能开销。
让我们想要执行案例的b c有三个变量。我们可以这样做:
CASE WHEN a = 1 AND b = 1 AND c = 1 THEN '1'
WHEN a = 0 AND b = 0 AND c = 1 THEN '0'
ELSE '0' END,
答案 7 :(得分:2)
我经历了这个并且发现所有答案都非常酷,但是想要添加@deejers给出的答案
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
你可以选择ELSE作为非强制性的,它在许多情况下非常有用。
答案 8 :(得分:0)