mysql每个类别的总和和计数追加到匹配的类别行

时间:2018-06-24 16:27:42

标签: mysql sql select

我正试图派生出一个能解决这个问题的MySQL查询:

product | sold
milk    |  6
milk    |  4
bread   |  3
bread   |  2
bread   |  2

对此;

product | sold | total order   | Total sold
milk    |  2   |       2       |     6
milk    |  4   |       2       |     6
bread   |  3   |       3       |     7
bread   |  2   |       3       |     7
bread   |  2   |       3       |     7

我已经能够获得总和的查询,但没有问题,但是我似乎无法将它作为与产品匹配的新列加入。这有可能吗?我已经尝试过WITH ROLLUP,但它只是创建了另一行,而不是我想要的。

1 个答案:

答案 0 :(得分:1)

您可以将此表上的简单查询与汇总查询结合在一起:

SELECT a.product, a.sold, b.total_order, b.total_sold
FROM   mytable a
JOIN   (SELECT   product, COUNT(*) AS total_order, SUM(sold) AS total_sold
        FROM     mytable
        GROUP BY product) b ON a.product = b.product