如何仅返回ID不重复且另一列具有匹配值的行?

时间:2019-06-11 13:50:13

标签: sql postgresql

我有一个表,需要检查是否存在多个<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="ticket.css" /> <title>Document</title> </head> <body> <section class="section-ticket"> <div class="left"> <button class="left-button">Back</button> <div class="event"> <div class="event-date"> Jan <br /> 5 </div> <h2>Soundcity MVP Award Festival</h2> <h2>Eko Hotel, Victorial Island Lagos</h2> <p> Event description goes here and more description for other things goes here and more and more so I cant say them all. </p> </div> <div class="share"> <p>Share Event</p> <i class="fas fas-facebook"></i> </div> </div> <div class="right"> <div> <h1>Hello</h1> </div> </div> </section> </body> </html> 和不同的/* Base reset styles */ *, *::before, *::after { padding: 0; margin: 0; box-sizing: inherit; } html { font-size: 62.5%; } body { box-sizing: border-box; } .section-ticket { display: grid; grid-template-columns: 1fr 1fr; height: 100vh; } .left { background-color: red; padding: 5.9rem 5.4rem 6.5rem 10rem; display: flex; flex-direction: column; align-items: flex-start; /* position: relative; */ } .right { background-color: blue; padding: 9.1rem 10rem 19.4rem 5.9rem; } .left-button { background: #f5f5f5; padding: 0.4rem 3rem; font-size: 2rem; cursor: pointer; border: none; outline: none; margin-bottom: 8.3rem; } .event { /* display: flex; */ /* flex-direction: column; */ /* justify-content: flex-start; */ /* width: 100%; */ } .event-date { /* display: flex; */ display: inline-block; /* justify-content: flex-end; */ /* position: absolute; */ /* width: 100%; */ text-align: center; text-transform: uppercase; font-size: 2.5rem; padding: 1rem 2.4rem; background-color: #ffbb00; box-shadow: 0 0 1.3rem rgba(0, 0, 0, 0.016); margin-bottom: 2.3rem; } .event h2 { font-size: 3.5rem; margin-bottom: 1rem; font-family: 'Helvetica'; } .event p { font-size: 2rem; margin-bottom: 13.8rem; } .share { font-size: 2rem; } ,并返回只有记录并且有{ ids列中的{1}}。

例如使用此表:

types

我想返回以下结果:

ids

由于这些只有一个包含试验的记录。如果trial包含试用和购买商品,我希望排除这些行。

3 个答案:

答案 0 :(得分:1)

可以通过内部查询来完成

select * from t where id IN (select id from t group by id having count(*) <= 1) AND trial = 'trial';

答案 1 :(得分:0)

我认为您不想要存在

select t.*
from t
where t.type = 'trial' and
      not exists (select 1 from t t2 where t2.id = t.id and t2.type <> 'trial');

如果您只想满足此条件的id,我建议进行汇总:

select t.*
from t
group by t.id
having sum( (t.type <> 'trial')::int ) = 0;

答案 2 :(得分:0)

使用JOIN的另一种选择。子查询将结果限制为唯一的id值,然后WHERE子句进一步将其过滤为您感兴趣的type值。

select 
  t.id,
  t.type
from
  @table as t
JOIN
  (
    select
      id
    from @table
    group by id
    having count(*)=1
  ) as d
    on d.id = t.id
where type = 'trial';

返回问题中的结果集。