简体   繁体   English

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

[英]SQL - Does row match max of sums

I am getting a little tripped up with a SQL query. 我对SQL查询有些了解。 Here is some background. 这是一些背景。

Schema: 架构:

Product(pid, price, color),
Order(cid, pid, quantity),
Customer(cid, name, age)

I want to get the pid of the most ordered product (greatest quantity). 我想获取订购最多的产品(最大数量)的PID。

I have managed to determine the max value with: 我设法用以下方法确定最大值:

Select Max(total) 
From (Select Sum(quantity) as total 
      From Orders Group By pid) as Totals

but I am getting stuck trying to match which products are in this subquery. 但是我在尝试匹配该子查询中的产品时陷入困境。 Here is what I have tried: 这是我尝试过的:

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

This says that q is an unknown column. 这表示q是未知列。

Any suggestions on how I could do this or do it better? 关于如何做或做得更好的任何建议?

you can do a JOIN along with GROUP BY like 你可以和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;

In your posted query it's erroring q is an unknown column cause q is a column alias which you are trying to use in WHERE condition; 在您发布的查询中,这是错误的q is an unknown column因为q是您要在WHERE条件下尝试使用的列别名; which is not allowed. 这是不允许的。

You should be able to simply include the PID in the original query because you are grouping on it. 您应该能够在原始查询中简单地包含PID ,因为您正在对其进行分组。 Then ORDER BY and and get only the top result using LIMIT 1 . 然后按ORDER BY并使用LIMIT 1仅获得最高结果。

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

Here's one way you can do it using a subquery with limit : 这是使用带有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
)

If you want only one most ordered product, then Karl's answer is fine. 如果您只想要一种订购最多的产品,那么卡尔的答案很好。 If you want all that have the same quantity, then: 如果您希望所有这些都具有相同的数量,那么:

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