Best way to do nested case statement logic in SQL Server

前端 未结 9 1399
误落风尘
误落风尘 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
    

提交回复
热议问题