gpt4 book ai didi

mysql sum and count per category append to matching category 行

转载 作者:行者123 更新时间:2023-11-29 07:31:33 26 4
gpt4 key购买 nike

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

最佳答案

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

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

关于mysql sum and count per category append to matching category 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com