我有以下查询:
Select emp_id, emp_name, department, salary
from tbl_employee emp
where (
CASE
when emp.department = 'C'
then (select count(*) from (SELECT 'Y' iscommissioner
FROM tbl_emp_department ted
where ted.department = emp.department ))
when emp.department = 'C'
then (select count(*) from (SELECT 'Y' iscommissioner
FROM tbl_emp_department ted
where ted.department = emp.department
and ted.id = 7))
END) > 0
我收到以下错误:
emp.department invalid identifier
我做错了什么?为什么我不能在case语句的where子句中使用表别名访问该列?
有什么想法吗?
答案 0 :(得分:2)
这与case
语句无关。问题是相关子查询的范围规则。它们只嵌套一层深。 Here是此问题的另一个问题。
对于您的示例,您不需要嵌套子查询。你可以这样做:
where (CASE when emp.department = 'C'
then (select count(*)
from tbl_emp_department ted
where ted.department = emp.department
)
when emp.department = 'C'
then (select count(*)
from tbl_emp_department ted
where ted.department = emp.department and ted.id = 7
)
END) > 0
但是,因为你的查询没有意义(两个when
子句的条件相同,我怀疑你的实际查询可能更复杂。你可能必须找到另一种方法来做你做的事情想要,使用显式连接和聚合或使用分析函数。