Best way to do nested case statement logic in SQL Server

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

    Wrap all those cases into one.


    SELECT
        col1,
        col2,
        col3,
        CASE
            WHEN condition1 THEN calculation1 
            WHEN condition2 THEN calculation2
            WHEN condition3 THEN calculation3
            WHEN condition4 THEN calculation4
            WHEN condition5 THEN calculation5
            ELSE NULL         
        END AS 'calculatedcol1',
        col4,
        col5 -- etc
    FROM table
    

提交回复
热议问题