views:

40

answers:

2

I have a statement which is complicated like this:

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  

I want to simplify this into something like this, is it possible:

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  
+4  A: 

Try this:

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
     )

In standard SQL, you are restricted to one condition per column.

Frank
Actually my calculation " X.ColB / denominator as X.colB" is more complicated, with a nested case, which also has a subtraction in one of the cases, than what I have shown above.
Needs Help
@Needs Can you show your actual query then so we don't waste time on answers irrelevant to your needs?
Martin Smith
@Needs Help: This approach can be adapted, as Martin's answer below shows.
Frank
A: 

You say in a comment that your actual needs are different from that presented in your question.

One other approach which might help readability/maintainability is to push the complicated condition statement into a CTE then you can check a simpler condition in the main query rather than repeating the complex one.

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  
Martin Smith
I like this approach better.
Needs Help