Best way to do nested case statement logic in SQL Server

前端 未结 9 1357
误落风尘
误落风尘 2020-11-29 15:23

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

相关标签:
9条回答
  • 2020-11-29 15:59

    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
    
    0 讨论(0)
  • 2020-11-29 16:02

    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

    0 讨论(0)
  • 2020-11-29 16:02

    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

    0 讨论(0)
提交回复
热议问题