繁体   English   中英

SQL-行是否匹配总和的最大值

[英]SQL - Does row match max of sums

我对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条件下尝试使用的列别名; 这是不允许的。

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

SELECT
    pid
   ,Sum(quantity) as total 
FROM
    Orders 
GROUP BY 
    pid
ORDER BY      
    Sum(quantity)
LIMIT 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
)

如果您只想要一种订购最多的产品,那么卡尔的答案很好。 如果您希望所有这些都具有相同的数量,那么:

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
                       );

暂无
暂无

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

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