PostgreSQL的返回多行,如果一行满足条件
问题描述:
我有如下表:PostgreSQL的返回多行,如果一行满足条件
表名:耶
id | tagname | value
----+---------+---------
0 | Farbe | Gelb
0 | Preis | 1.15
0 | Thema | Herbst
1 | Farbe | Maigrün
1 | Preis | 1.15
1 | Thema | Herbst
2 | Farbe | Schwarz
2 | Preis | 1.15
2 | Thema | Sommer
我想要的是得到一个ID的所有行的哪一个或更多的条件得到满足,一个或多个条件得不到满足。 如果,例如,我希望所有id
他们在tagname='Preis'
,value='1.15'
和tagname=Thema
,value='Herbst'
满足表中的行,但不希望id
其中tagname='Farbe'
,value='Schwarz'
变为真。结果应该是这样的:
id | tagname | value
----+---------+---------
0 | Farbe | Gelb
0 | Preis | 1.15
0 | Thema | Herbst
1 | Farbe | Maigrün
1 | Preis | 1.15
1 | Thema | Herbst
当包含至少一个条件得到满足,包括在条件满足的id
所有行要在结果中。 但是,如果满足排除条件中的至少一个条件,则结果中不应包含相应的id
的行。
答
如果你只是想在id
S,你可以这样做:
select id
from yay
group by id
having sum(case when tagname = 'preis' and value = '1.15' then 1 else 0 end) > 0 and
sum(case when tagname = 'Thema' and value = 'Herbst' then 1 else 0 end) > 0 and
sum(case when tagname = 'Farbe' and value = 'Schwarz' then 1 else 0 end) = 0;
每个条件计算匹配的行数。由于> 0
,前两个要求至少有一个匹配(每个)匹配id
。第三个说没有匹配,因为= 0
。
您可以通过加入回得到原始数据:
select yay.*
from yay join
(select id
from yay
group by id
having sum(case when tagname = 'preis' and value = '1.15' then 1 else 0 end) > 0 and
sum(case when tagname = 'Thema' and value = 'Herbst' then 1 else 0 end) > 0 and
sum(case when tagname = 'Farbe' and value = 'Schwarz' then 1 else 0 end) = 0
) yid
on yay.id = yid.id;
这就是我一直在寻找。谢谢! – 2014-09-30 17:36:40