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

qvsjd97n  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(304)

我正在尝试派生一个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 但它只是创建了另一行,而不是我想要的。

rjzwgtxy

rjzwgtxy1#

您可以将此表上的简单查询与上的聚合查询联接起来:

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

相关问题