在PostgreSQL中展平Left Join结果

问题描述

我有eventtagsfiltervalues。所以我有类似的东西

eventtags:
event_id,key_id,value_id,event_date

filtervalues:
value_id,key,value,counts_seen

假设我在eventtags表中有2个事件与多个键,值对一起报告

event_id | key_id | value_id | event_date
---------+--------+----------+-----------
1        |   20   |    32    | xx-xx-xxxx
1        |   21   |    34    | xx-xx-xxxx
2        |   20   |    35    | yy-yy-yyyy
2        |   21   |    39    | yy-yy-yyyy

对应的filter_value表具有以下数据

values_id |  key  | value | counts_seen
----------+-------+-------+----------
32        | type  | staff | 52
34        | tag   | tag1  | 13
35        | type  | user  | 10
39        | tag   | tag2  | 35

现在,基于此,我在下面的查询中尝试合并来自两个表的数据

SELECT t.event_id as Event_Id,DATE (t.event_date) as Event_Date,v.key as Keys,v.value as Values
   FROM eventtags t
   LEFT JOIN filtervalues as v ON t.value_id = v.id

结果是这样

Event_Id |  Keys  |  Values  | Event_Date
---------+--------+----------+-----------
1        |  type  |   staff  | xx-xx-xxxx
1        |  tag   |   tag1   | xx-xx-xxxx
2        |  type  |   user   | yy-yy-yyyy
2        |  tag   |   tag2   | yy-yy-yyyy

我希望数据采用以下格式

Event_Id |  type  |   tag   | Event_Date
---------+--------+---------+-----------
1        | staff  |  tag1   | xx-xx-xxxx
2        | user   |  tag2   | yy-yy-yyyy

我需要对上面的查询进行哪些更改以获得这种格式?

注意:我无法使用数据透视表,因为我正在使用的系统不支持它们。

非常感谢您的帮助

解决方法

针对没有数据透视表(交叉表)的情况尝试以下操作:

SELECT t.event_id as Event_Id,max(v.value) filter (where v.key='type') as "type",max(v.value) filter (where v.key='tag') as "tag",DATE (t.event_date) as Event_Date
   FROM eventtags t
   LEFT JOIN filtervalues as v ON t.value_id = v.id
   group by t.event_id,t.event_date

DEMO

以上仅适用于PostgreSQL 9.4及更高版本。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...