SELECT Col1,Col2,Col3 FROM Table WHERE Column1具有重复项

时间:2013-01-09 16:29:39

标签: tsql sql-server-2008-r2

我想显示表格中col1重复的所有行。

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
|    1 |    0 |    0 |
|    1 |    1 |    1 |
|    2 |    0 |    0 |
|    3 |    0 |    0 |
|    3 |    1 |    1 |
|    4 |    0 |    0 |
+------+------+------+

结果应该是:

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
|    1 |    0 |    0 |
|    1 |    1 |    1 |
|    3 |    0 |    0 |
|    3 |    1 |    1 |
+------+------+------+

我尝试了一些没有运气的疑问,所以我在这里寻求你的帮助。

6 个答案:

答案 0 :(得分:6)

根据您的sql server版本,您可以使用:

select col1, col2, col3
from
(
  select col1, col2, col3,
    count(col1) over(partition by col1) cnt
  from yourtable
) src
where cnt > 1

请参阅SQL Fiddle with Demo

答案 1 :(得分:3)

select t.col1, t.col2, t.col3
from mytable t join (select col1 
                     from mytable 
                     group by col1 
                     having count(*) > 1) t2
  on t.col1 = t2.col1

答案 2 :(得分:3)

让我再添加一个变体解决方案。如果您的pk列具有UNIQUEPRIMARY KEY约束,则可以使用:

select col1, col2, col3
from <yourTable> t1
where exists
  (select *
   from <yourTable> t2
   where t2.col1 = t1.col1
     and t2.pk <> t1.pk
  ) ;

答案 3 :(得分:2)

select col1, col2, col3
from <yourTable> t1
where exists
  (select null
   from <yourTable> t2
   where t2.col1 = t1.col1
   group by t2.col1
   having count(*) > 1)

sqlFiddle

答案 4 :(得分:2)

如果表的名称是T5,那么使用:

SELECT COL1, COL2, COL3
FROM T5
WHERE COL1 IN
(
    SELECT COL1
    FROM T5
    GROUP BY COL1
    HAVING COUNT(COL1)>=2
)

我检查过,上面不应该使用任何非标准的SQL。我假设其他人就是这种情况。

答案 5 :(得分:1)

猜猜我太迟了......但左边加入怎么样......

SQLFIDDLE DEMO

查询:

SELECT DISTINCT x.col1, x.col2, x.col3 
FROM ab y
LEFT JOIN 
ab x
ON y.col1=x.col1 and ( y.col2<> x.col2
                    OR x.col3<>y.col3 )
where not (x.col3 is null)
and not (x.col2 is null)
;

结果:

COL1    COL2    COL3
1       0   0
1       1   1
3       0   0
3       1   1