CASE WHEN语句中需要SQL别名列名

时间:2018-08-07 14:30:54

标签: sql sql-server sql-server-2014

如何引用别名“新日期”?我不断收到“无效的列名'NewDate'”错误。

CASE
    WHEN p.Program IN ('program1') THEN (date_needed + 10)
    WHEN p.Program IN ('program2') THEN (date_needed + 20)
END AS [NewDate]

CASE 
    WHEN date_needed < [NewDate] THEN 'Program On Time' 
    ELSE 'Program Late'
END AS [Modified New Date]

4 个答案:

答案 0 :(得分:3)

由于逻辑查询的处理顺序,因此不可能在同一块中引用NewDate列。为此,您可以使用通用表表达式,如下所示:

WITH Base_CTE
AS
(
SELECT CASE
    WHEN p.Program IN ('program1') THEN (date_needed + 10)
    WHEN p.Program IN ('program2') THEN (date_needed + 20)
END AS [NewDate], date_nedded
FROM tablename
)
SELECT CASE 
    WHEN date_needed < [NewDate] THEN 'Program On Time' 
    ELSE 'Program Late'
END AS [Modified New Date]
FROM Base_CTE; 

答案 1 :(得分:1)

嵌套CASE

SELECT
CASE 
    WHEN CASE
           WHEN p.Program IN ('program1') THEN (date_needed + 10)
           WHEN p.Program IN ('program2') THEN (date_needed + 20)
         END < [NewDate] THEN 'Program On Time' 
    ELSE 'Program Late'
END AS [Modified New Date]

或使用子查询或CTE ...

WITH CTE AS(
SELECT
CASE
    WHEN p.Program IN ('program1') THEN (date_needed + 10)
    WHEN p.Program IN ('program2') THEN (date_needed + 20)
END AS [NewDate], date_needed
FROM YourTable)

SELECT
CASE 
    WHEN date_needed < [NewDate] THEN 'Program On Time' 
    ELSE 'Program Late'
END AS [Modified New Date]
FROM CTE

答案 2 :(得分:0)

您可以使用applysubquery

select p.*, (case when p.date_needed < p1.NewDate 
                  then 'Program On Time' 
                  else 'Program Late' 
              end) as [Modified New Date]
from table p cross apply
     ( values (  case when p.Program = 'program1' 
                      then (date_needed + 10)
                      when p.Program = 'program2' 
                      then (date_needed + 20)
                  end
              )
     ) p1(NewDate);

答案 3 :(得分:0)

为此,我是apply的粉丝:

SELECT v.date_needed,
       (CASE WHEN v.date_needed < [NewDate] THEN 'Program On Time' 
             ELSE 'Program Late'
        END) AS [Modified New Date]
FROM t CROSS APPLY
     (VALUES (CASE WHEN t.Program IN ('program1') THEN (date_needed + 10)
                   WHEN t.Program IN ('program2') THEN (date_needed + 20)
              END)
     ) v(date_needed)