SQL: Alias Column Name for Use in CASE Statement

前端 未结 11 1772
悲哀的现实
悲哀的现实 2020-12-04 21:38

Is it possible to alias a column name and then use that in a CASE statement? For example,

SELECT col1 as a, CASE WHEN a = \'test\' THEN \'yes\' END as value          


        
相关标签:
11条回答
  • 2020-12-04 21:40

    I think that MySql and MsSql won't allow this because they will try to find all columns in the CASE clause as columns of the tables in the WHERE clause.

    I don't know what DBMS you are talking about, but I guess you could do something like this in any DBMS:

    SELECT *, CASE WHEN a = 'test' THEN 'yes' END as value FROM (
       SELECT col1 as a FROM table
    ) q
    
    0 讨论(0)
  • 2020-12-04 21:42

    make it so easy.

    select columnnameshow = (CASE tipoventa
    when 'CONTADO' then 'contadito'
    when 'CREDITO' then 'cred'
    else 'no result'
    end) from Promocion.Promocion 
    
    0 讨论(0)
  • 2020-12-04 21:43
    SELECT
        a AS [blabla a],
        b [blabla b],
        CASE c
            WHEN 1 THEN 'aaa'
            WHEN 2 THEN 'bbb'
            ELSE 'unknown' 
        END AS [my alias], 
        d AS [blabla d]
    FROM mytable
    
    0 讨论(0)
  • 2020-12-04 21:44

    I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

    With localView1 as (
     select c1,
            c2,
            c3,
            c4,
            ((c2-c4)*(3))+c1 as "complex"
       from realTable1) 
       , localView2 as (
     select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
            complex * complex as formula2    
       from localView1)
    select *
    from localView2
    
    0 讨论(0)
  • 2020-12-04 21:50
    • If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End

    • If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End

    From tablename

    Thanks Mr.Buntha Khin

    0 讨论(0)
  • 2020-12-04 21:56

    @OMG Ponies - One of my reasons of not using the following code

    SELECT t.col1 as a, 
         CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
    FROM TABLE t;
    

    can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like

    Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)') 
    as XMLTagAlias from Table
    
    0 讨论(0)
提交回复
热议问题