Using If else in SQL Select statement

后端 未结 11 1614
感情败类
感情败类 2020-12-24 05:35

I have a select statement which will return 2 columns.

ID | IDParent

Then in my program I have to test if IDParent is < 1 then use

相关标签:
11条回答
  • 2020-12-24 06:02

    sql server 2012

      with
      student as 
    (select sid,year from (
    values (101,5),(102,5),(103,4),(104,3),(105,2),(106,1),(107,4)
    ) as student(sid,year)
    )
    select iif(year=5,sid,year) as myCol,* from student
    
    
     myCol  sid year
    101 101 5
    102 102 5
    4   103 4
    3   104 3
    2   105 2
    1   106 1
    4   107 4
    
    0 讨论(0)
  • 2020-12-24 06:03
    select 
    CASE WHEN IDParent is < 1 then ID else IDParent END as colname 
    from yourtable
    
    0 讨论(0)
  • 2020-12-24 06:04
    SELECT CASE WHEN IDParent < 1 
                THEN ID 
                ELSE IDParent 
           END AS colname 
    FROM yourtable
    
    0 讨论(0)
  • 2020-12-24 06:04

    Here is some example using CASE WHEN

    SELECT 
        CASE WHEN A > 1 THEN
                'Greater than 1'
        END  
    FROM TRIANGLES
    

    .

    SELECT 
        CASE WHEN A > 1 THEN
                A
        END  
    FROM TRIANGLES
    

    .

    SELECT 
        CASE WHEN A > 1 and B > 1 THEN
                'Greater than 1'
        END  
    FROM TRIANGLES
    

    .

    SELECT 
        CASE WHEN A > 1 THEN
                'greater than 1'
             ELSE
                'less than 1'
        END  
    FROM TRIANGLES
    

    .

    SELECT 
        CASE WHEN A > 1 THEN
                'greater than 1'
             ELSE CASE WHEN A >= 0 THEN
                          'greater than or equal 0'
                       ELSE
                          'less than 0'
                  END        
        END  
    FROM TRIANGLES;
    

    Hope this helps

    0 讨论(0)
  • 2020-12-24 06:07

    Here are two ways "IF" Or "CASE".

    SELECT IF(COLUMN_NAME = "VALUE", "VALUE_1", "VALUE_2") AS COLUMN_NAME 
    FROM TABLE_NAME;
    

    OR

    SELECT (CASE WHEN COLUMN_NAME = "VALUE" THEN 'VALUE_1' ELSE 'VALUE_2' END) AS COLUMN_NAME 
    FROM TABLE_NAME;
    
    0 讨论(0)
提交回复
热议问题