How do I do multiple CASE WHEN conditions using SQL Server 2008?

前端 未结 10 1900
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 09:57

What I\'m trying to do is use more than one CASE WHEN condition for the same column.

Here is my code for the query:

   SELECT   Url=\'\',
                    


        
相关标签:
10条回答
  • 2020-11-27 10:32

    There are two formats of case expression. You can do CASE with many WHEN as;

    CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
          WHEN Col1 = 2 THEN 2
          ...
          ELSE 0 END as Qty
    

    Or a Simple CASE expression

    CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END
    

    Or CASE within CASE as;

    CASE  WHEN Col1 < 2 THEN  
                        CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
          WHEN Col1 = 2 THEN 2
          ...
          ELSE 0 END as Qty
    
    0 讨论(0)
  • 2020-11-27 10:37

    Just use this one, You have to use more when they are classes.

    SELECT   Url='',
             p.ArtNo,
             p.[Description],
             p.Specification,
             CASE 
             WHEN 1 = 1 or 1 = 1 
                THEN 1 
             WHEN 2 = 2
                 THEN 2
             WHEN 3 = 3
                  THEN 3
              ELSE 0 
            END as Qty,
            p.NetPrice,
            [Status] = 0
      FROM  Product p (NOLOCK)
    
    0 讨论(0)
  • 2020-11-27 10:38

    I had a similar but it was dealing with dates. Query to show all items for the last month, works great without conditions until Jan. In order for it work correctly, needed to add a year and month variable

    declare @yr int
    declare @mth int
    
    set @yr=(select case when month(getdate())=1 then YEAR(getdate())-1 else YEAR(getdate())end)
    set @mth=(select case when month(getdate())=1 then month(getdate())+11 else month(getdate())end)
    

    Now I just add the variable into condition: ...

    (year(CreationTime)=@yr and MONTH(creationtime)=@mth)
    
    0 讨论(0)
  • 2020-11-27 10:38

    Its just that you need multiple When for a single case to behave it like if.. Elseif else..

       Case when 1=1       //if
       Then
        When 1=1              //else if
         Then.... 
        When .....              //else if
        Then 
        Else                      //else
       ....... 
         End
    
    0 讨论(0)
提交回复
热议问题