我对 SQL 查询有点迷惑。这是一些背景。
架构:
Product(pid, price, color),
Order(cid, pid, quantity),
Customer(cid, name, age)
我想获取订购最多的产品(最大数量)的 pid。
我已经设法确定了最大值:
Select Max(total)
From (Select Sum(quantity) as total
From Orders Group By pid) as Totals
但我在尝试匹配此子查询中的哪些产品时遇到了困难。这是我尝试过的:
Select pid, SUM(quantity) as q
From Orders
Where q in (
Select Max(total)
From (Select Sum(quantity) as total
From Orders
Group By pid) as Totals
)
Group By pid
这表示 q 是未知列。
关于我如何做到这一点或做得更好有什么建议吗?
最佳答案
你可以像GROUP BY
一样做一个JOIN
select p.*
from product p
join
(select pid from Order
group by pid having quantity = max(quantity)
) tab on p.pid = tab.pid;
在您发布的查询中它出错 q is an unknown column
因为 q
是您尝试在 WHERE
条件下使用的列别名;这是不允许的。
关于mysql - SQL - 行是否匹配总和的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139879/