选择每组中2列中具有相等值的所有行

时间:2018-06-15 19:31:14

标签: sql h2

考虑下表

ID   || YEAR  || TERM  || NAME   || UNIT    
----------------------------------------
1    || 1985  || 1     || MARIE  || 01VS
1    || 1986  || 2     || MARIE  || 01VS
1    || 1986  || 2     || MARIE  || 07GB 
1    || 1986  || 3     || MARIE  || 07GB
2    || 1992  || 1     || AVALON || 01VS
2    || 1992  || 2     || AVALON || 01VS
2    || 1992  || 3     || AVALON || 01VS
3    || 2001  || 1     || DENIS  || 08HK
3    || 2001  || 1     || DENIS  || 07GB
3    || 2001  || 2     || DENIS  || 08HK
3    || 2002  || 1     || DENIS  || 08HK

我想在H2中编写一个sql查询,它会返回每个 ID 的所有行,其中 YEAR TERM 具有相等的值。因此,对于上表,结果应如下所示:

ID   || YEAR  || TERM  || NAME   || UNIT    
----------------------------------------
1    || 1986  || 2     || MARIE  || 01VS
1    || 1986  || 2     || MARIE  || 07GB
3    || 2001  || 1     || DENIS  || 08HK
3    || 2001  || 1     || DENIS  || 07GB

3 个答案:

答案 0 :(得分:1)

您可以使用exists

select t.*
from table t
where exists (select 1 
              from table t1 
              where t1.id = t.id and t1.year = t.year and 
                    t.term = t1.term and t1.unit <> t.unit
             );

答案 1 :(得分:0)

我认为像下面这样的东西会起作用

select *
from table t
where exists (select id, term from table t2 
where t2.id = t.id 
and t2.term = t.term
group by id, term
having count(*) > 1)

然而,如果表具有某种主键,则会更容易。

答案 2 :(得分:0)

如何使用GROUP BY和HAVING将表连接到子查询?

select t.*
from yourtable t
join 
(
    select ID, YEAR, TERM
    from yourtable 
    group by ID, YEAR, TERM
    having count(*) > 1
) d on (d.ID = t.ID and d.YEAR = t.YEAR and d.TERM = t.TERM);