简体   繁体   English

'WITH' 子句不适用于 in 运算符

[英]'WITH' clause does not work with in operator

I have a simple query:我有一个简单的查询:

with MaxSal AS (SELECT MAX(Salary), DepartmentId FROM Employee GROUP BY DepartmentId)
SELECT Department.Name AS "Department", Employee.Name AS "Employee", Employee.Salary AS "Salary" FROM Employee
JOIN Department ON Department.Id = Employee.DepartmentId
WHERE (Employee.Salary, Employee.DepartmentId) in MaxSal;

It should create a MaxSal temporary table and then in the WHERE section it should check whether the Salary, DepId are inside said table.它应该创建一个MaxSal临时表,然后在WHERE部分中检查Salary, DepId是否在所述表内。 Unfortunately, this query gives me ORA-00920: invalid relational operator which I guess is referring to the in operator.不幸的是,这个查询给了我ORA-00920: invalid relational operator ,我猜它指的是in运算符。 If I put the Sub-query directly instead of first putting it in a temp table, everything works as expected.如果我直接放置子查询而不是先将其放入临时表中,那么一切都会按预期工作。
Can somebody tell me why it isn't working with the WITH clause?有人能告诉我为什么它不能与WITH子句一起使用吗?

You need a table reference to refer to the CTE and that, in turn, requires a FROM clause.您需要一个表引用来引用 CTE,而这又需要一个FROM子句。 You can do what you want using a subquery您可以使用子查询做您想做的事

WITH MaxSal AS (
      SELECT MAX(Salary) as max_salary, DepartmentId
      FROM Employee
      GROUP BY DepartmentId
     )
SELECT d.Name AS Department, e.Name AS Employee, 
       e.Salary AS Salary
FROM Employee e JOIN
     Department d
     ON d.Id = e.DepartmentId
WHERE (e.Salary, e.DepartmentId) in (SELECT max_salary, DepartmentId) FROM MaxSal);

That said, RANK() is much simpler:也就是说, RANK()要简单得多:

SELECT Department, Name AS Employee, Salary
FROM (SELECT e.*, d.Name as Department,
             RANK() OVER (PARTITION BY d.id ORDER BY e.Salary DESC) as seqnum
      FROM Employee e JOIN
           Department d
           ON d.Id = e.DepartmentId
     ) ed
WHERE seqnum = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM