SQL:将多行组合到基于非主键的单行

发布于 2025-02-11 18:57:19 字数 692 浏览 2 评论 0原文

我有这样的表:

|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        |

我希望该表格为:

| order_id | quantity_111  | quantity_112  | quantity_113 |
| A        | 2             | 3             |  1           |
| C        | null          | 2             |  null        |
| B        | 5             | 1             |  null        |

在其中我们将使用产品ID制作数量列,我们只有3个固定的产品ID。

请帮助我找出SQL查询以实现此输出。

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.

Kindly help me figure out the SQL query to achieve this output.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光无声 2025-02-18 18:57:19

你可以做一个穷人的枢纽。例如:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文