where 语句中不存在别名表



问题来自 https://code.dennyzhang.com/sales-analysis-i

我的解决方案是:

select seller_id
from (select seller_id, sum(price) price
from Sales
group by seller_id) S
# where S.price = max(S.price)
where S.price = (select max(price) from S)

但是,控制台给了我错误消息:

Table 'test.s' doesn't exist

我将最后一行代码替换为

where S.price = 0

这不会给我任何错误消息,这意味着S表确实存在。所以我的问题是这个错误消息是如何来的?

S是对可用于限定列的表的引用。 它不能在FROM子句中使用。

您可以使用 CTE 执行所需的操作:

with S as (
select seller_id, sum(price) as price
from Sales
group by seller_id
) 
select seller_id
from S
where S.price = (select max(price) from S)

最新更新