MySql:找到SUM值的MAX?

时间:2014-12-11 17:52:19

标签: mysql sum max

我想找出每个类别中项目的最高数量。

我有一张名为"产品"如下图所示:

+----------+-------+-----+
| Category | Item  | Qty |
+----------+-------+-----+
| A        | A100  |  15 |
| A        | A100  |   7 |
| A        | A101  |   3 |
| A        | A101  |   9 |
| B        | B100  |   6 |
| B        | B100  |   7 |
| B        | B101  |   8 |
| B        | B101  |  13 |
+----------+-------+-----+

执行查询后

SELECT Category, Item, SUM(Qty) as Quantity FROM products GROUP BY Category,Item;

我得到的结果如下

+----------+-------+----------+
| Category | Item  | Quantity |
+----------+-------+----------+
| A        | A100  |       22 |
| A        | A101  |       12 |
| B        | B100  |       13 |
| B        | B101  |       21 |
+----------+-------+----------+

现在我想在每个类别中找到最高数量的项目,我希望输出如下:

+----------+-------+----------+
| Category | Item  | Quantity |
+----------+-------+----------+
| A        | A100  |       22 |
| B        | B101  |       21 |
+----------+-------+----------+

我该怎么做?我已经尝试了下面的查询,但我只是得到了'好的'结果没有给我任何输出表。

select Category, Item, max(Qty) as Quantity from products group by OD_type  having Quantity = (select sum(Qty) from products group by Item);

如何获得所需的输出,如上表所示? 如果这不是一个好问题,或者我的问题不够明确,我很抱歉。 任何帮助将不胜感激,谢谢!

3 个答案:

答案 0 :(得分:3)

这会更容易使用viewcommon-table-expression(如果mysql支持它)。

SELECT t.category, t.item, t.quantity
FROM (
    SELECT Category, Item, SUM(Qty) Quantity 
    FROM products 
    GROUP BY Category, Item
  ) t JOIN (
    SELECT category, max(quantity) Quantity
    FROM (
      SELECT Category, Item, SUM(Qty) Quantity 
      FROM products 
      GROUP BY Category,Item
    ) t
    GROUP BY category
  ) t2 ON t.Category = t2.Category and t.quantity = t2.quantity

基本想法是按每个类别和项目分组sum,然后按每个类别获取max(sum),然后join返回原始sum } query ...

答案 1 :(得分:1)

您需要将其用作子查询,如果有两个具有相同最大值的项目,您将只获得其中一个。

SELECT Category, Item, Max(Quantity) as MaxVal
FROM
(
SELECT Category, Item, SUM(Qty) as Quantity 
FROM products 
GROUP BY Category,Item
) T
GROUP BY Category

答案 2 :(得分:0)

这看起来很难看,我看到mysql有更好的方法......但我相信它有用......

SELECT A.category, A.Item, A.Quantity
FROM (SELECT Category, Item, SUM(Qty) as Quantity 
      FROM products 
      GROUP BY Category,Item) A
INNER JOIN (Select Max(B.quantity) Quantity, B.Category 
            FROM 
              (SELECT Category, SUM(Qty) as Quantity 
               FROM products 
               GROUP BY Category, Item) B
            GROUP BY Category) C
  ON A.Category=C.Category
 and A.Quantity = C.Quantity

我想使用一个窗口集,但似乎mysql不支持它们。因为我们必须首先聚合数据然后才能获得最大值,内部选择是必要的..我想使用CTE来提高可读性,但是MySQL并不支持它们......

我可能会创建表A,B作为视图并调用视图以使其更容易阅读长期运行。