Sql 由唯一值联接的同一表中作为列的行
我正在努力构建一个查询-结果应该来自两个表:Sql 由唯一值联接的同一表中作为列的行,sql,postgresql,Sql,Postgresql,我正在努力构建一个查询-结果应该来自两个表: 值表: eventid | elementid | value ------------------------------- 10 | 1 | 1234 11 | 1 | 1234 11 | 2 | True eventid | eventuid ------------------- 10 | abcdef 11 | ghijk
值
表:
eventid | elementid | value
-------------------------------
10 | 1 | 1234
11 | 1 | 1234
11 | 2 | True
eventid | eventuid
-------------------
10 | abcdef
11 | ghijkg
因此,values
表可以为同一elementid
具有多个值
事件
表:
eventid | elementid | value
-------------------------------
10 | 1 | 1234
11 | 1 | 1234
11 | 2 | True
eventid | eventuid
-------------------
10 | abcdef
11 | ghijkg
我的目标是构建一个显示
value1 | value2 | eventuid
-----------------------------
True | 1234 | abcdef
True | 5678 | ghijkg
- A列:
element1的值
- B列:
element2的值
- C列:eventuid
elementid=1
的值是唯一的时,即对于相同的elementid=1
没有具有相同值的eventid
s
我的尝试是先创建一个视图:
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
s-
然后从该视图中读取,但我无法“透视”这些值:
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;
您已经完成了创建要包含的唯一事件列表的更复杂部分 从那里很容易得到你想要的桌子
--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'
“元素1的值”“-表中没有元素1或元素2。请澄清。请澄清唯一性标准。您说过“但仅当elementid=1的值是唯一的时”-id为1的两个记录的
值字段都是“1234”,因此它不会是唯一的;但是,您会说“即,对于相同的elementid=1,没有具有相同值的eventid”-那么这是否意味着,值
字段必须是每个eventid
和elementid
组合的唯一字段?当我只需要显示行其中elementid=2且value=True
时,您建议添加什么?目前,无论该值如何,我都能看到每一行。实际上,我认为视图
没有正确返回eventuid
,其中elementid=1的值
是唯一的。它根据您的注释更新了初始视图,并在SELECT语句中添加了一个过滤示例