简体   繁体   English

如何在SQL中选择具有重复列值的所有行

[英]How to select all rows with duplicated column value in SQL

I have a table with a few repetitions in col1: 我在col1中有一个表,其中有一些重复:

co1, col2, col3
a, d, f
r, h, d
e, g, h
z, k, m
e, s, t
a, b, c
e, k, t

Thanks to this post , I can select all col1 values which are repeated 由于这篇文章 ,我可以选择所有重复的col1值

SELECT col1
FROM mytable
GROUP BY col1
HAVING ( COUNT(col1) > 1 )

How can I select all rows with a repeated col1 value and order them by col1? 如何选择所有具有重复col1值的行并按col1对其进行排序? The expected result looks like this: 预期结果如下所示:

co1, col2, col3
a, d, f
a, b, c
e, g, h
e, s, t
e, k, t

Use EXISTS 使用EXISTS

SELECT *
FROM   mytable a
WHERE  EXISTS (SELECT 1
               FROM   mytable b
               WHERE  a.col1 = b.col1
               HAVING Count(col1) > 1) 
Order by col1

Another way 其他方式

SELECT *
FROM   (SELECT *,
               Count(1)OVER( partition BY col1) AS cnt
        FROM   mytable) a
WHERE  cnt > 1
ORDER  BY col1 

You can use a window function for that: 您可以为此使用窗口函数:

select co1, col2, col3
from (
  select co1, col2, col3, count(*) over (partition by col1) as cnt
  from the_table
) t
where cnt > 1
order by col1;

You can Inner Join the result with the original table like this: 您可以将结果与原始表进行Inner Join ,如下所示:

select t1.* 
from your_table t1
inner join (
    select col1
    from your_table
    group by col1
    having count(col1) > 1 ) t2
on t1.col1 = t2.col1
order by t1.col1;
Select * 
From ( Select * ,count(*) over (Partition By Col1) as cnt from t) t
Where cnt>1
        Select co1,col2,col3 From 
    ( Select * ,count(*) over (Partition By Co1) as cnt from #b) a
 Where cnt>1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM