Postgresql如果一行满足条件,则返回多行

时间:2014-09-30 17:24:26

标签: sql postgresql filter

我有下表:

表名:yay

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的所有行以及不满足一个或多个条件的所有行。 例如,如果我希望表idtagname='Preis'value='1.15'tagname=Thema满足所有value='Herbst'及其行,但不要; t 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的行。

1 个答案:

答案 0 :(得分:2)

如果你只想要id,你可以这样做:

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;

每个条件计算匹配行的数量。由于id,前两个要求> 0至少有一个匹配(每个)。第三个说没有匹配,因为= 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;
相关问题