sql别名在CASE语句中使用的列名

时间:2013-03-21 10:50:03

标签: sql-server-2008

我有一个SQL查询,如下所示,

select Site,DataSource,
(SELECT CASE 
   WHEN DataSource = 'RFQ' THEN 'ChangeOperator' 
   ELSE 'SameOperator' 
  END) AS OperatorScenario,

  (SELECT CASE 
   WHEN OperatorScenario = 'ChangeOperator' THEN '1' 
   ELSE '022' 
  END) AS OperatorScenario2
from tablename

当我执行此查询时,我将异常作为无效的列名称OperatorScenario。所以我尝试在第二个查询中使用别名中的单个代码,如下所示,

(SELECT CASE 
   WHEN 'OperatorScenario' = 'ChangeOperator' THEN '1' 
   ELSE '022' 
  END) AS OperatorScenario2

然后它总是执行其他部分。请给我一些建议。 问候 桑杰塔

3 个答案:

答案 0 :(得分:7)

主要问题是您无法在同一查询中引用别名。你还有一个括号和一个额外的SELECT关键字,看起来像一个我不相信你想要的子查询(你没有FROM子句)。

您可以再次复制整个内容(在此过程中修复查询):

SELECT Site, DataSource,
    CASE 
       WHEN DataSource = 'RFQ' THEN 'ChangeOperator' 
       ELSE 'SameOperator' 
    END AS OperatorScenario,

   CASE 
       WHEN 
           CASE 
               WHEN DataSource = 'RFQ' THEN 'ChangeOperator' 
               ELSE 'SameOperator' 
           END = 'ChangeOperator' THEN '1' 
       ELSE '022' 
  END AS OperatorScenario2
from tablename

或者,简化:

SELECT Site, DataSource,
    CASE 
       WHEN DataSource = 'RFQ' THEN 'ChangeOperator' 
       ELSE 'SameOperator' 
    END AS OperatorScenario,

   CASE 
       WHEN DataSource = 'RFQ' THEN '1' 
       ELSE '022' 
   END AS OperatorScenario2
from tablename

或使用CTE(再次修复您的查询):

WITH cte AS
(
    SELECT Site, DataSource,
    CASE 
       WHEN DataSource = 'RFQ' THEN 'ChangeOperator' 
       ELSE 'SameOperator' 
    END AS OperatorScenario,
    FROM tablename
)
SELECT Site, DataSource, OperatorScenario,
    CASE 
        WHEN OperatorScenario = 'ChangeOperator' THEN '1' 
        ELSE '022' 
    END AS OperatorScenario2
FROM cte

答案 1 :(得分:3)

您无法在此查询中访问同一级别的别名,无论是使用子查询还是使用cte:

WITH cte 
     AS (SELECT site, 
                datasource, 
                CASE 
                  WHEN datasource = 'RFQ' THEN 'ChangeOperator' 
                  ELSE 'SameOperator' 
                END AS OperatorScenario 
         FROM   dbo.tablename) 
SELECT site, 
       datasource, 
       operatorscenario, 
       CASE 
         WHEN operatorscenario = 'ChangeOperator' THEN '1' 
         ELSE '022' 
       END AS OperatorScenario2 
FROM   cte 

请注意,我还删除了额外的parantheses并在CASE中选择。

答案 2 :(得分:0)

我在开头设置了别名,如下所示:

SELECT [ALIAS] = CASE....

你的意思是:

SELECT Site, DataSource,   
   [OperatorScenario] = CASE 
       WHEN DataSource = 'RFQ' THEN 'ChangeOperator' ELSE 'SameOperator' 
   END,

   [OperatorScenario2] = CASE 
       WHEN DataSource = 'RFQ' THEN '1' ELSE '022' 
   END
from tablename