简体   繁体   English

SQL 查询以数量分组项目,然后显示总数量

[英]SQL query to group items with their quantity then show a total quantity

I have the following data that I'd like to rearrange using an SQL query:我想使用 SQL 查询重新排列以下数据:

在此处输入图像描述

I'd like to group the same order_id to show it like the following:我想将相同的 order_id 分组以显示如下:

99996 | 99996 | 63 - 2, 62 - 2 | 63 - 2, 62 - 2 | 4 4

So that's looking for the items in the same order, showing the product id and quantity, then showing the total of all the quantities for each order.因此,这是在同一订单中查找商品,显示产品 ID 和数量,然后显示每个订单的所有数量的总和。

Usually I'd attempt this and show my code but I don't even know where to start!通常我会尝试这个并显示我的代码,但我什至不知道从哪里开始!

Use two levels of aggregation:使用两个级别的聚合:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM