我调试了以下代码很长时间,并意识到我的错误是最初在子查询中的变量之前省略了t.
。我们必须在子查询中包含别名,这是一条规则吗?
注意:正如下面的答案所说,真正的问题不是子查询中缺少别名,而是使用了保留的工作";排名"如果";rnk";则不需要子查询中的别名。
WITH t AS(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Salary ASC) AS "rank" FROM
Employee)
SELECT t.Id, t.Company, t.Salary
FROM t
JOIN (SELECT t.Company, MAX(t.rank) AS maxRank FROM t GROUP BY t.Company) s
ON t.Company=s.Company
WHERE CASE WHEN s.maxRank%2=0 THEN t.rank=s.maxRank/2 OR t.rank=s.maxRank/2+1
ELSE t.rank=CEIL(s.maxRank/2) END
不需要,只要不需要区分子查询和外部查询即可。
但请不要为列使用保留字,否则您需要封装
WITH t AS(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Company ORDER BY Salary ASC) AS "rank" FROM
Employee)
SELECT t.Id, t.Company, t.Salary
FROM t
JOIN (SELECT Company, MAX(`rank`) AS maxRank FROM t GROUP BY Company) s
ON t.Company=s.Company
WHERE CASE WHEN s.maxRank%2=0 THEN t.rank=s.maxRank/2 OR t.rank=s.maxRank/2+1
ELSE t.rank=CEIL(s.maxRank/2) END