0 votes
1 view
in SQL by (20.3k points)

I'm currently 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 statements, but it is getting messy. Is there a better (more organized and/or readable) way?

(I am using Microsoft SQL Server, 2005)

A simplified example:

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

1 Answer

0 votes
by (40.4k points)

Try using COALESCE trick, like this:

SELECT COALESCE(

  CASE WHEN condition1 THEN calculation1 ELSE NULL END,

  CASE WHEN condition2 THEN calculation2 ELSE NULL END,

  etc...

)

If you want to learn SQL commands visit these SQL Commands Cheat Sheet.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...