SQL - 行匹配最大值

时间:2014-11-26 01:33:41

标签: mysql sql database

我的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是一个未知的列。

关于我如何做到这一点或做得更好的任何建议?

4 个答案:

答案 0 :(得分:1)

您可以JOINGROUP BY一样

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条件中使用的列别名;这是不允许的。

答案 1 :(得分:1)

您应该能够在原始查询中简单地包含PID,因为您正在对其进行分组。然后ORDER BY并使用LIMIT 1获得最高结果。

SELECT
    pid
   ,Sum(quantity) as total 
FROM
    Orders 
GROUP BY 
    pid
ORDER BY      
    Sum(quantity)
LIMIT 1

答案 2 :(得分:1)

使用带有limit的子查询,您可以采用以下方法:

select o.pid, sum(o.quantity)
from `order` o
group by o.pid
having sum(o.quantity) = 
(
    select sum(quantity) 
    from `order`
    group by pid
    order by sum(quantity) desc
    limit 1
)

答案 3 :(得分:1)

如果您只想要一个最有序的产品,那么卡尔的答案就可以了。如果您想要所有具有相同数量的产品,那么:

select pid, sum(quantity) as quantity
from orders o
group by pid
having sum(quantity) = (select max(quantity)
                        from (select sum(quantity) as quantity
                              from orders o
                              group by pid
                             ) q
                       );