提问者:小点点

一个SQL查询,将物料按数量分组,然后显示总数量


我想使用SQL查询重新排列以下数据:

我想对相同的order_id进行分组,以如下所示:

99996 63-2,62-2 4

这就是寻找同一订单中的物品,显示产品id和数量,然后显示每个订单的所有数量的总和。

通常我会尝试这样做并显示我的代码,但我甚至不知道从哪里开始!


共1个答案

匿名用户

使用两个级别的聚合:

select order_id, group_concat(product_id, ' - ', cnt separator ', ') as products, sum(cnt) as total
from (select order_id, product_id, count(*) as cnt
      from t
      group by order_id, product_id
     ) op
group by order_id;