Sql 如何基于ID合并行

Sql 如何基于ID合并行,sql,postgresql,pivot,inner-join,aggregate-functions,Sql,Postgresql,Pivot,Inner Join,Aggregate Functions,我有两张桌子,一张是这种结构的: id | user_id | field_type_id | value ------------------------------------- 1 | 1 | 1 | John Doe 2 | 1 | 2 | 0800 111 222 3 | 1 | 3 | johndoe@aol.comm 4 | 2 | 1

我有两张桌子,一张是这种结构的:

id | user_id | field_type_id | value
-------------------------------------
1  | 1       | 1             | John Doe
2  | 1       | 2             | 0800 111 222
3  | 1       | 3             | johndoe@aol.comm
4  | 2       | 1             | Alice Cooper
5  | 2       | 2             | 0800 222 333
6  | 3       | 1             | Ben Sparks
7  | 3       | 3             | ben@gmail.com
我还有另一个表,它的字段类型ID是:

field_type_id | name
-----------------------------
1             | Name
2             | Phone Number
3             | Email Address
我可以运行哪种查询来获得以下输出:

user_id | name         | phone        | email
--------------------------------------------------
1       | John Doe     | 0800 111 222 | Johndoe@aol.com
2       | Alice Cooper | 0800 222 333 | NULL
3       | Ben Sparks   | NULL         | ben@gmail.com

假设user_id是唯一的(否则抛出一个DISTINCT),您可以根据第一个表上的user id进行分组,然后将每个类型的用户id与其自身连接起来。看起来是这样的

WITH UniqueUsers AS (SELECT user_id FROM table1 GROUP BY user_id)
 
SELECT UniqueUsers.user_id,
  names.value AS name,
  phone.value AS phone,
  email.value AS email
FROM UniqueUsers
LEFT JOIN table1 AS names ON UniqueUsers.user_id = names.user_id AND names.field_type_id = 1
LEFT JOIN table1 AS phone ON UniqueUsers.user_id = phone.user_id AND phone.field_type_id = 2
LEFT JOIN table1 AS email ON UniqueUsers.user_id = email.user_id AND email.field_type_id = 3

您可以
加入
,并以条件聚合为轴心:

select a.user_id
    max(a.value) filter(where f.name = 'name')  as name,
    max(a.value) filter(where f.name = 'phone') as phone,
    max(a.value) filter(where f.name = 'email') as email
from attributes a
inner join fieldtypes f on f.field_type_id = a.field_type_id
group by userid

您是否忘记了CTE中的
不同的
?我假设用户id是唯一的,并更新了答案。