如何在sql中达到以下要求

时间:2019-01-29 10:00:28

标签: sql

enter image description here我有下面的表格

结果集应包含4,5,因为其计数为(c2)和(c3)> 1

4 个答案:

答案 0 :(得分:4)

您可以使用exists

select t.*
from table t
where exists (select 1 from table t1 where t1.col2 = t.col2 and t1.col1 <> t.col1);

答案 1 :(得分:1)

JOIN子查询,该子查询返回重复的col2值:

select t1.*
from tablename t1
join (select col2 from tablename
      group by col2 having count(*) > 1) t2
    on t1.col2 = t2.col2

答案 2 :(得分:1)

我将使用窗口功能:

select t.*
from (select t.*,
             count(*) over (partition by c2) as c2_cnt,
             count(*) over (partition by c3) as c3_cnt
      from t
     ) t
where c2_cnt > 1 and c3_cnt > 1;

答案 3 :(得分:0)

随着您更改要求,我更改了查询

select t1.* from table_name t1 where 
    exists( select 1 from table_name t2 where t2.col2=t1.col2
                                and t2.c3=t1.c3
                              group by t2.c2,t2.c3
                              having count(*)>1
              )