[英]SQL: Combining multiple rows to a single row based on non primary key
I've a table like this:我有一张这样的桌子:
|Id | order_id | product_id | quantity |
|1 | A | 111 | 2 |
|2 | A | 112 | 3 |
|3 | A | 113 | 1 |
|4 | C | 112 | 2 |
|5 | B | 111 | 5 |
|6 | B | 112 | 1 |
And I'm expecting the table as:我期待这张桌子:
| order_id | quantity_111 | quantity_112 | quantity_113 |
| A | 2 | 3 | 1 |
| C | null | 2 | null |
| B | 5 | 1 | null |
Where we will make quantity columns with product ids, we only have 3 fixed product ids.在我们将使用产品 ID 创建数量列的地方,我们只有 3 个固定的产品 ID。
Kindly help me figure out the SQL query to achieve this output.请帮助我找出实现此输出的 SQL 查询。
You can do a poor man's pivot.你可以做一个穷人的支点。 For example:例如:
select
order_id,
max(case when product_id = 111 then quantity end) as q111,
max(case when product_id = 112 then quantity end) as q112,
max(case when product_id = 113 then quantity end) as q113
from t
group by order_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.