[英]how to merge the same result from GROUP_CONCAT on MYSQL
now im doing some query using GROUP_CONCAT on mysql.现在我在 mysql 上使用 GROUP_CONCAT 做一些查询。 for example
例如
i have table "sales_orders"我有表“sales_orders”
+----------+----------+------------+
| order_id | quantity | product_id |
+----------+----------+------------+
| 1 | 1 | 101|
| 1 | 1 | 102|
| 2 | 1 | 103|
| 2 | 1 | 104|
| 3 | 1 | 101|
| 3 | 1 | 102|
+--------+------------+------------+
my query like this我的查询是这样的
SELECT order_id, count(quantity) AS qty, GROUP_CONCAT(DISTINCT product_id ORDER BY product_id ASC ) AS product_id FROM sales_orders GROUP BY order_id
and the output like this和这样的输出
+----------+-----+------------+
| order_id | qty | product_id |
+----------+-----+------------+
| 1| 2|101,102 |
| 2| 2|103,104 |
| 3| 2|101,102 |
+----------+-----+------------+
if we see, product_id have same result for 101,102
.如果我们看到, product_id 对
101,102
有相同的结果。 how do i can manage to merge that same result become like this with count for qty also.我如何才能设法将相同的结果与数量合并成这样。
+-----+------------+
| qty | product_id |
+-----+------------+
| 4|101,102 |
| 2|103,104 |
+-----+------------+
maybe order_id for me is not important to display.也许 order_id 对我来说显示并不重要。 please help
请帮忙
First observation of mine is that the quantity may at times be more than 1. For that reason I would suggest use sum instead of count for quantity我的第一个观察是数量有时可能超过 1。出于这个原因,我建议使用 sum 而不是 count 来表示数量
Next query using a sub-query.使用子查询的下一个查询。
SELECT sum(qty) AS quantity, product_id FROM (SELECT order_id, sum(quantity) AS qty, GROUP_CONCAT(DISTINCT product_id ORDER BY product_id ASC ) AS product_id FROM sales_orders GROUP BY order_id) as derived_table GROUP BY product_id SELECT sum(qty) AS 数量, product_id FROM (SELECT order_id, sum(quantity) AS qty, GROUP_CONCAT(DISTINCT product_id ORDER BY product_id ASC ) AS product_id FROM sales_orders GROUP BY order_id) asderived_table GROUP BY product_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.