SQL查询在一列中获取具有2个或更多重复项的行,而在另外两列中没有重复项?

时间:2016-12-17 17:51:17

标签: sql sql-server

So say my table is:
#3 6 4#
#4 5 6#
#4 6 4#
#8 6 4#
#1 2 3#
#1 3 2#
#4 5 6#

我想获取第一列中有2个或更多重复项的行,而另外2个中没有重复项。

So my result should be:
#1 2 3#
#1 3 2#

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用count() over()

执行此操作

rextester:http://rextester.com/TVW19929

create table temp (a int, b int, c int);
insert into temp values (3,6,4) ,(4,5,6) ,(4,6,4) ,(8,6,4) ,(1,2,3) ,(1,3,2) ,(4,5,6);

with cte as (
  select t.a, t.b, t.c
      , aCount = count(*) over (partition by t.a)
      , bCount = count(*) over (partition by t.b)
      , cCount = count(*) over (partition by t.c)
    from temp t
    )
select a, b, c
  from cte
  where aCount > 1
    and bCount = 1
    and cCount = 1;