Reference an alias elsewhere in the SELECT list

后端 未结 3 1318
盖世英雄少女心
盖世英雄少女心 2020-11-30 14:51

I have the following query:

    select FirstName, LastName,
    Case
     When LastName = \'Jones\'
     then \'N/A\'
    End as Other,
    Case 
      When          


        
相关标签:
3条回答
  • 2020-11-30 15:35

    You can also do this with a common table expression (CTE):

    ;WITH cte AS 
    (
    SELECT 
        firstname, 
        lastname, 
        CASE WHEN lastname = 'Jones' THEN 'N/A' 
        END AS Other 
    FROM @t
    ) 
    SELECT 
        firstname, 
        lastname, 
        CASE WHEN other IS NOT NULL THEN 1 
            ELSE 0 
        END AS Flag 
    FROM cte
    
    0 讨论(0)
  • 2020-11-30 15:35

    You will have to use a SELECT in a SELECT:

    SELECT FirstName, LastName, Other, 
        Case When Other is not null 
             then 1 
             else 0 END as Flag
    FROM 
    (
        select FirstName, LastName,
            Case
             When LastName = 'Jones'
             then 'N/A'
            End as Other
        from yourTable
    ) x
    

    Or you can reuse the CASE statement for the Other field when evaluating the Flag field:

    select FirstName, 
        LastName,
        Case 
            When LastName = 'Jones'
            then 'N/A'
        End as Other,
        case when LastName = 'Jones' -- your Other CASE code here
            then 1
            else 0
        END as flag 
    from yourTable
    
    0 讨论(0)
  • 2020-11-30 15:36

    You can't refer to an alias outside of SELECT and ORDER BY because of the way a query is parsed. Typical workaround is to bury it in a derived table:

    SELECT 
      FirstName, LastName, Other, 
      Flag = CASE WHEN Other IS NOT NULL THEN 1 ELSE 0 END
    FROM 
    (
      SELECT FirstName, LastName,
        CASE WHEN LastName = 'Jones'
         THEN 'N/A'
        END AS Other
      FROM dbo.table_name
    ) AS x;
    
    0 讨论(0)
提交回复
热议问题