使用键作为列将主 table 的数据与键值属性连接形成另一个 table

Join master table's data with key-value attributes form another table using keys as columns

我有一个名为 Events 的 PostgreSQL table,如下所示:

+----+----------+------------+
| id | event    | created_at |
+----+----------+------------+
| 1  | pageview | 2019-03-29 |
+----+----------+------------+
| 2  | purchase | 2019-03-28 |
+----+----------+------------+

另一个 table 叫 EventAttributes

+----------+---------+-------------------------------+
| event_id | key     | value                         |
+----------+---------+-------------------------------+
| 1        | url     | https://www.whosebug.com |
+----------+---------+-------------------------------+
| 2        | product | Apple                         |
+----------+---------+-------------------------------+
| 2        | user    | Nick                          |
+----------+---------+-------------------------------+

我想获取所有事件以及关联的属性作为列,如下所示:

+----+----------+------------+-------------------------------+---------+------+
| id | event    | created_at | url                           | product | user |
+----+----------+------------+-------------------------------+---------+------+
| 1  | pageview | 2019-03-29 | https://www.whosebug.com | null    | null |
+----+----------+------------+-------------------------------+---------+------+
| 2  | purchase | 2019-03-29 | null                          | Apple   | Nick |
+----+----------+------------+-------------------------------+---------+------+

我想我需要使用一个枢轴 table 但我不确定该怎么做。

欢迎提供有关该主题的任何帮助或相关文章。

您可以进行条件聚合:

select e.id, e.event, e.created_at, 
       max(case when ea.key = 'url' then ea.value end) as url,
       max(case when ea.key = 'product' then ea.value end) as product,
       max(case when ea.key = 'user' then ea.value end) as user
from Events e inner join
     EventAttributes ea
     on ea.event_id = e.id
group by e.id, e.event, e.created_at;

使用条件聚合:

SELECT
    e.id, 
    e.event, 
    e.created_at,
    MAX(CASE WHEN ea.key = 'url' THEN ea.value END) url,
    MAX(CASE WHEN ea.key = 'product' THEN ea.value END) product,
    MAX(CASE WHEN ea.key = 'user ' THEN ea.value END) user 
FROM Events e
INNER JOIN EventAttributes ea ON ea.event_id  = e.id
GROUP BY 
    e.id, 
    e.event, 
    e.created_at