sql case / if语句

时间:2010-07-30 19:23:54

标签: sql-server-2005 case

我有一个像这样复杂的陈述:

select x.ColA as ColA  

 , case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then X.ColB / 100 else  X.ColB / 900 End as ColB  
 , case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then X.ColC / 100 else  X.ColC / 900 End as ColC  
 , case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then X.ColD / 100 else  X.ColD / 900 End as ColD  
 , case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then X.ColE / 100 else  X.ColE / 900 End as ColE  

From TableA  

我想将此简化为类似的东西,是否可能:

select x.ColA as ColA  

case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then  

 ,  X.ColB / 100 as ColB  
 ,  X.ColC / 100 as ColC  
 ,  X.ColD / 100 as ColD  
 ,  X.ColE / 100 as ColE  

Else  

 ,  X.ColB / 900 as ColB  
 ,  X.ColC / 900 as ColC  
 ,  X.ColD / 900 as ColD  
 ,  X.ColE / 900 as ColE  

End  

From TableA  

2 个答案:

答案 0 :(得分:4)

试试这个:

select x.ColA,
       X.ColB / denominator as colB,
       X.ColC / denominator as colC,
       X.ColD / denominator as colD,
       X.ColE / denominator as colE
from (
     select x.ColA, X.ColB, X.ColC, X.ColD, X.ColE,
            case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then 100 else 900 End as denominator
     From TableA
     )

在标准SQL中,每列限制为一个条件。

答案 1 :(得分:0)

您在评论中说,您的实际需求与您提出的问题不同。

另一种可能有助于提高可读性/可维护性的方法是将复杂的条件语句推送到CTE中,然后您可以在主查询中检查更简单的条件,而不是重复复杂的条件。

WITH cte AS
(
select case when x.optA = 'AB' or x.optA = 'FG' or x.optA = 'LM' or x.optA = 'QR' then 1 else 0 end as cond,
ColB,
ColC,
ColD,
ColE
FROM x
)

select x.ColA as ColA ,
case when cond=1 then  X.ColB / 100 else  X.ColB / 900 As ColB
case when cond=1 then  X.ColC / 100 else  X.ColC / 900 As ColC
case when cond=1 then  X.ColD / 100 else  X.ColD / 900 As ColD
case when cond=1 then  X.ColE / 100 else  X.ColE / 900 As ColE
From cte