您好我正在做一个子查询来获取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
答案 0 :(得分: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
答案 1 :(得分: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。