5

我有一个如下的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

当我执行此查询时,我收到异常为 Invalid column name OperatorScenario。所以我尝试在第二个查询中使用别名中的单个代码,如下所示,

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

所以它总是执行 else 部分。请给我一些建议。问候桑吉塔

4

3 回答 3

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
于 2013-03-21T10:56:29.140 回答
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 

请注意,我还删除了额外的括号并在CASE.

于 2013-03-21T10:57:08.260 回答
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
于 2015-09-28T15:17:36.723 回答