Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将名称/值表(枚举、属性)合并到postgres中的一行中_Sql_Postgresql - Fatal编程技术网

Sql 将名称/值表(枚举、属性)合并到postgres中的一行中

Sql 将名称/值表(枚举、属性)合并到postgres中的一行中,sql,postgresql,Sql,Postgresql,我们有许多表是属性或枚举,可以方便地将其转换为一行,其中列名是名称,值是下表中的值: thedb=> select * from nv_props; id | name | value ----+------------------+------------------ 2 | Serial Number | 01234567 3 | Part | 2KEWL4U 4 | Model

我们有许多表是属性或枚举,可以方便地将其转换为一行,其中列名是名称,值是下表中的值:

thedb=> select * from nv_props;
 id |       name       |      value       
----+------------------+------------------
  2 | Serial Number    | 01234567
  3 | Part             | 2KEWL4U
  4 | Model            | CustomersTest
  1 | Firmware         | .03-b
类似于名称-值对的转置

 Serial Number    | Serial Number    | Serial Number    | Firmware
------------------+------------------+------------------+------------
 01234567         | 2KEWL4U          | CustomersTest    |.03-b     
名称具有唯一约束,无法找到简单的解决方案

谢谢,
MJ

如果你找不到一个简单的解决方案,也许你不知道在分组查询中使用条件聚合(case表达式)实现“枢轴”的通用方法

select 
       min(id) as gid
     , max(case when name = 'Serial Number' then value end) as col1
     , max(case when name = 'Part'          then value end) as col2
     , max(case when name = 'Model'         then value end) as col3
     , max(case when name = 'Firmware'      then value end) as col4
from nv_props
where id in (1,2,3,4)
您可以(重新)命名您认为合适的列


您在示例数据中没有提供的是跨4行的“公共列”,这通常是分组依据。我相信您可以将此示例应用于您的具体情况。

您正在尝试
透视您的结果。如果你知道潜在列的数量,那就很简单了(有很多这样的例子)。如果没有,那么您将考虑使用
动态sql
。随便看看。