sql查询将项目与其数量分组,然后显示总数量

qojgxg4l  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(381)

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

我想将相同的订单id分组,如下所示:
99996 | 63 - 2, 62 - 2 | 4
这就是寻找相同订单中的商品,显示产品id和数量,然后显示每个订单的所有数量的总和。
通常我会尝试这样做,并显示我的代码,但我甚至不知道从哪里开始!

pexxcrt2

pexxcrt21#

使用两个聚合级别:

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;

相关问题