I\'m writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.
I\'m currently using nested case stateme
I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.
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
a user-defined function may server better, at least to hide the logic - esp. if you need to do this in more than one query
This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops