如何从表中选择重复的列数据

时间:2014-11-24 12:15:12

标签: sql sql-server tsql

有表格:

col1  col2   col3  col4  col5
test1   1     13    15    1
test2   1     13    15    4
test3   2     7      3    5
test4   3     11    14    18
test5   3     11    14    8
test6   3     11    14    11

想要选择col1,col2,col3,col4重复的col2,col3,col4数据 例如,它必须是:

col1  col2   col3  col4 
test1   1     13    15    
test2   1     13    15  
test4   3     11    14  
test5   3     11    14
test6   3     11    14 

怎么做?

4 个答案:

答案 0 :(得分:3)

假设SQL-Server> = 2005,您可以使用COUNT(*) OVER

WITH CTE AS
(
    SELECT col1, col2, col3, col4, cnt = COUNT(*) OVER (PARTITION BY col2, col3, col4)
    FROM dbo.TableName t
)
SELECT col1, col2, col3, col4
FROM CTE WHERE cnt > 1

Demo

答案 1 :(得分:0)

如果我理解正确:

select col1, col2, col3, col4
from table t
where exists (select 1 from table t2 where t2.col1 = t.col1 and t2.col1 <> t.col1) and
      exists (select 1 from table t2 where t2.col2 = t.col2 and t2.col1 <> t.col1) and
      exists (select 1 from table t2 where t2.col3 = t.col3 and t2.col1 <> t.col1);

答案 2 :(得分:0)

简单加入可以工作

select m1.col1,m1.col2,m1.col3,m1.col4 from Mytable m1
join Mytable m2
on m1.col2 =m2.col2
and m1.col3=m2.col3
and m1.col4 =m2.col4

答案 3 :(得分:0)

您可以使用以下代码:

SELECT * FROM your_table

MINUS

SELECT DISTINCT * FROM your_table

编辑:抱歉,这仅适用于完整的重复项。如果要排除第一列,可以使用

SELECT col2,col3,col4 FROM your_table

MINUS

SELECT DISTINCT col2,col3,col4 FROM your_table

然后使用表格本身joinON为主键)。