0

我想显示 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 |
+------+------+------+

我已经尝试了一些没有运气的查询,所以我在这里寻求您的帮助。

4

6 回答 6

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

于 2013-01-09T16:33:21.967 回答
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
于 2013-01-09T16:32:02.827 回答
3

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

select col1, col2, col3
from <yourTable> t1
where exists
  (select *
   from <yourTable> t2
   where t2.col1 = t1.col1
     and t2.pk <> t1.pk
  ) ;
于 2013-01-09T16:42:53.670 回答
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

于 2013-01-09T16:31:15.000 回答
2

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

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

我检查过,上面不应该使用任何非标准的 SQL。我假设其他人也是如此。

于 2013-01-09T16:41:54.040 回答
1

我想我来晚了..但是左连接怎么样...

SQLFIDDLE 演示

询问:

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
于 2013-01-09T16:47:29.463 回答