来自同一表的列作为行,并通过唯一值连接

时间:2018-12-05 17:30:28

标签: sql postgresql

我正在努力构建查询-结果应该来自两个表:

values表:

eventid | elementid |   value
-------------------------------
10      |  1        |   1234
11      |  1        |   1234
11      |  2        |   True

因此,values表可以为同一elementid具有多个值。

events表:

eventid | eventuid
-------------------
10      |  abcdef
11      |  ghijkg 

我的目标是建立一个可显示的查询

value1  |   value2  |   eventuid
-----------------------------
True    |  1234     |   abcdef
True    |  5678     |   ghijkg
  • A列:element1
  • 的值
  • B列:element2
  • 的值
  • C列:事件

,但前提是elementid=1的值是唯一的,即对于相同的eventid,没有elementid=1的值相同。

我的尝试是先创建一个视图:

create view unique_event as
select distinct e.eventuid, count(v.value)
from events e
join values v on e.eventid = v.eventid
where v.elementid = 1
group by e.eventuid
having count(v.value) = 1;

这似乎仅返回不同的eventuid起作用- 然后从该视图中读取,但我无法“透视”值:

select v.value as value1, e.eventuid
from events e
join value v on v.eventid = e.eventid
where e.eventuid in (select eventuid from unique_event)
and v.elementid in (1, 2)
group by e.eventuid, v.value;

1 个答案:

答案 0 :(得分:0)

您已经通过创建要包括的唯一事件列表完成了更复杂的部分!

从那里很容易获得想要的表。

--note that you do not need "distinct" since you are already grouping by the event ids

create view unique_event as
select  max(e.eventuid::text) as eventuid 
 , v.value
 , max(e.eventid) as e.eventid)
from events e
join values v on e.eventid = v.eventid
where v.elementid = 1
group by v.value
having count(e.eventid) = 1;

select e.eventuid
--since we want only one row for the event, we have to tell it which value we want of the value column
--since max ignores null, this will give us the non-null value
-- but if there is only record for the event, min would work just as well
, max(case when v.elementid = 1 then value end) as value1
, max(case when v.elementid = 2 then value end) as value2
from unique_event e
join values v on e.eventid = v.eventid
group by e.eventuid
having max(case when v.elementid = 2 then value end) = 'True'