首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在postgresql中将一个多行的表转换为一个一行多列的表?

如何在postgresql中将一个多行的表转换为一个一行多列的表?
EN

Stack Overflow用户
提问于 2021-08-11 14:10:05
回答 2查看 32关注 0票数 1

我有一个表,其中包含一些以行为单位的规格

代码语言:javascript
复制
product_id  |   spec      |   value   |
------------+-------------+-----------+
  prod-1    |   speed     |    30     |
  prod-1    |   weight    |    20     |
  prod-1    |   power     |    500    |
  prod-1    |   autonomy  |    20     |

我想创建一个查询或函数,将其返回为

代码语言:javascript
复制
product_id   | speed  | weight  | power | autonomy |
-------------+--------+---------+-------+----------+
  prod-1     |  30    |    20   |  500  |    20    |

为了在前端有更好的操控。

EN

回答 2

Stack Overflow用户

发布于 2021-08-11 14:18:40

使用扩展tablefunc中的crosstab函数将行转换为列:

代码语言:javascript
复制
SELECT *
FROM crosstab(
 'SELECT product_id, spec, value FROM specs' 
) AS ct(product_id int, speed int,  weight int, power int, autonomy int);

演示:db<>fiddle

票数 1
EN

Stack Overflow用户

发布于 2021-08-11 15:22:11

您可以使用条件聚合,它在Postgres中看起来很像:

代码语言:javascript
复制
select product_id,
       max(value) filter (where spec = 'weight') as weight,
       max(value) filter (where spec = 'speed') as speed,
       max(value) filter (where spec = 'power') as power,
       max(value) filter (where spec = 'autonomy') as autonomy
from specs s
group by product_id;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68743662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档