0

嗨,我正在做一个子查询来获取 cTL 列的值但是我需要子查询中的外列值才能正确响应,但是我收到错误,它无法识别 SC 和 RC 变量。有什么出路吗?

SELECT DISTINCT(cStoreCode) as SC
    ,cRetailerCode as RC
    , cStoreCode + ' - ' + cStoreName AS Store,
    x.TeamLead 
FROM
(
    SELECT cTL as TeamLead 
    FROM tblEmpSchedule 
    WHERE   cRepCode LIKE @repCode AND
        cClientCode LIKE @gCode AND
        cProjectCode LIKE @pCode AND
        cYear LIKE @year AND
        cCycleNo LIKE @cycleNo AND
        cRetailerCode LIKE @retailerCode AND
        cStoreCode = SC AND
        cRetailerCode = RC
 )x
,tblEmpSchedule 
WHERE cRepCode LIKE @repCode AND
    cClientCode LIKE @gCode AND
    cProjectCode LIKE @pCode AND
    cYear LIKE @year AND
    cCycleNo LIKE @cycleNo AND
    cRetailerCode LIKE @retailerCode AND
    cStoreCode <> '' AND cStoreCode is Not Null
ORDER BY cStoreCode
4

2 回答 2

1

看起来您需要在 SC/RC 周围加上单引号:

cStoreCode = 'SC' AND
cRetailerCode = 'RC'

编辑:

请检查以下内容是否可行:

SELECT cTL as TeamLead 
FROM tblEmpSchedule t1
INNER JOIN 
(
  SELECT DISTINCT(cStoreCode) SC
    , cRetailerCode RC
    , cStoreCode + ' - ' + cStoreName AS Store
  FROM tblEmpSchedule
)t2

  on t1.cTL = t2.cTL
WHERE t1.cRepCode LIKE @repCode 
  AND t1.cClientCode LIKE @gCode 
  AND t1.cProjectCode LIKE @pCode 
  AND t1.cYear LIKE @year 
  AND t1.cCycleNo LIKE @cycleNo 
  AND t1.cRetailerCode LIKE @retailerCode 
  AND (t1.cStoreCode <> '' AND t1.cStoreCode is Not Null)
  AND t1.cStoreCode = t2.SC
  AND t1.cRetailerCode = t2.RC
ORDER BY  t1.cStoreCode
于 2012-07-13T17:34:38.097 回答
1

不,您不能在 WHERE 子句中为这样的表达式引用别名。仅当来自内联视图或 CTE(在 FROM 子句中引用)时,才能在 WHERE 子句中引用表达式的别名。

DISTINCT 关键字的使用看起来很奇怪。不需要将 SELECT 列表中的第一个表达式用括号括起来。您的构造使它几乎看起来像是一个函数调用。(不是,DISTINCT 关键字适用于 SELECT 列表中的所有表达式)。

完全不清楚为什么在这里需要 JOIN 操作。

我讨厌用问题来回答问题,但是...您想通过使用内联视图从别名为 TeamLead 的 cTL 列中获取值来获得什么?这应该解决什么问题?为什么表需要被引用两次?

换个方式问同样的问题...

tblEmpSchedule 表上的查询返回的结果集有什么“错误”,比如这个?

SELECT DISTINCT s.cStoreCode             AS sc
     , s.cRetailerCode                   AS rc
     , s.cStoreCode + ' - ' + cStoreName AS Store
     , s.cTL                             AS TeamLead
  FROM tblEmpSchedule s
 WHERE s.cRepCode LIKE @repCode AND
       s.cClientCode LIKE @gCode AND
       s.cProjectCode LIKE @pCode AND
       s.cYear LIKE @year AND
       s.cCycleNo LIKE @cycleNo AND
       s.cRetailerCode LIKE @retailerCode AND
       s.cStoreCode <> ''
 ORDER BY s.cStoreCode

如果您可以解释为什么此查询返回的结果集与您需要的不同,那么我(或其他人)可能会提供帮助。正如您的问题所表明的那样,尚不清楚您要达到的目标。

注意:cStoreCode IS NOT NULL查询中的“”谓词是多余的。cStoreCode <> ''如果“ ”谓词返回 TRUE ,我们已经知道它不能为 NULL 。

于 2012-07-13T20:57:07.323 回答