SQL - CASE语句中的别名

时间:2016-02-24 14:43:49

标签: sql-server

我有这段代码(请看下面的内容)。我一直收到错误:“列名无效'SuppFinish2'

SELECT

CASE
    WHEN [RegFinish] IS NULL THEN ''
    ELSE [RegFinish]
END AS [RegFinish],

CASE
    WHEN [SuppFinish] IS NULL THEN ''
    ELSE [SuppFinish]
END AS [SuppFinish2],

CASE
    WHEN [RegFinish]<[SuppFinish2] THEN '1'
    ELSE '0'
END AS [TEST]

FROM TABLE

是因为[SuppFinish2]是别名吗?谢谢!

5 个答案:

答案 0 :(得分:2)

正如您所说,由于别名和别名列只能按顺序依据逻辑查询流顺序引用

with cte
as
(
SELECT
CASE
    WHEN [RegFinish] IS NULL THEN ''
    ELSE [RegFinish]
END AS [RegFinish],

CASE
    WHEN [SuppFinish] IS NULL THEN ''
    ELSE [SuppFinish]
END AS [SuppFinish2]
FROM TABLE
)
select 
CASE
    WHEN [RegFinish]<[SuppFinish2] THEN '1'
    ELSE '0'
END AS [TEST]
from cte

答案 1 :(得分:1)

为了引用别名列,您可以使用派生表(或CTE,但此处未显示)

Select *, CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST] From
(
SELECT

CASE
    WHEN [RegFinish] IS NULL THEN ''
    ELSE [RegFinish]
END AS [RegFinish],

CASE
    WHEN [SuppFinish] IS NULL THEN ''
    ELSE [SuppFinish]
END AS [SuppFinish2]
) T1
FROM TABLE

答案 2 :(得分:1)

您不能同时在SELECT子句中设置和访问别名。我建议使用CROSS APPLY重写您的查询:

SELECT t1.[RegFinish],
       t2.[SuppFinish],
       CASE
          WHEN t1.[RegFinish] < t2.[SuppFinish] THEN '1'
          ELSE '0'
       END AS [TEST]
FROM TABLE
CROSS APPLY (SELECT COALESCE([RegFinish], '') AS [RegFinish]) AS t1
CROSS APPLY (SELECT COALESCE([SuppFinish], '') AS [SuppFinish]) AS t2

答案 3 :(得分:1)

你不能在创建它们的同一级别使用这些别名,因为它们还不存在..用另一个选择包装你的查询:

SELECT * ,
       CASE
            WHEN [RegFinish]<[SuppFinish2] THEN '1'
            ELSE '0'
       END AS [TEST]
FROM (
    SELECT
        [ID],
        CASE
            WHEN [RegFinish] IS NULL THEN ''
            ELSE [RegFinish]
        END AS [RegFinish],
        CASE
            WHEN [SuppFinish] IS NULL THEN ''
            ELSE [SuppFinish]
        END AS [SuppFinish2],
    FROM TABLE)

答案 4 :(得分:1)

SELECT ISNULL([RegFinish],'') as  [RegFinish]
     , ISNULL([SuppFinish],'') as [SuppFinish2], CASE 
WHEN  
  ISNULL([RegFinish],'') < ISNULL([SuppFinish],'') THEN 1
                                                   ELSE 0 
END  AS [TEST]
FROM TABLE 

为什么不使用ISNULL而不是CASE?您的查询的问题是[SuppFinish2]是别名而不是列,只能在ORDER BY子句中使用