Best way to do nested case statement logic in SQL Server

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

    I went through this and found all the answers super cool, however wants to add to answer given by @deejers

        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         
        END AS 'calculatedcol1',
        col4,
        col5 -- etc
    FROM table
    

    you can make ELSE optional as its not mandatory, it is very helpful in many scenarios.

提交回复
热议问题