选择一列中具有重复值的行

时间:2013-05-30 11:31:01

标签: sql sql-server

在使用此表的SQL Server 2008 R2中:

CREATE TABLE mytest(
     id [bigint] IDENTITY(1,1) NOT NULL,
     code [bigint] NULL,
     sequence_number [int] NULL
);

此查询:

SELECT id, code, sequence_number
  FROM mytable

返回此数据:

 id     code    sequence_number
  1      381        0
  2      381        1
  3      382        0
  4      382        1
  5      383        0
  6      383        1
  7      383        1
  8      384        0
  9      384        1
  10     385        0
  11     385        1
  12     385        2
  13     386        0
  14     386        1
  15     386        1
  16     386        2
  17     387        0
  18     387        1
  19     387        1
  20     387        2
  21     387        3
  22     387        3
  23     388        0
  24     388        1
  25     388        1
  26     388        2
  27     388        2
  28     389        0
  29     389        1

我如何SELECT只是这些行:

7   383 1
15  386 1
19  387 1
22  387 3
25  388 1
27  388 2

这些是MAX(id)行,其中有多个记录具有相同的sequence_number。我想要代码和sequence_number的每个唯一组合的所有最高ID。

因此,实际上我只想选择“重复”的sequence_number记录。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

试试这个: -

 Select ID,code,sequence_number from
 (
  Select ID,
         code,
         [rn] = row_number() over (partition by code,sequence_number order by id),
         sequence_number
  from yourTable
 )s
 where rn > 1

SQL FIDDLE

中的演示

答案 1 :(得分:1)

select code,MAX(sequence_number) from mytest group by code

答案 2 :(得分:1)

使用此

SELECT 
    MAX(t1.Id) as ID, 
    t1.code, 
    t1.sequence_number
FROM mytest t1
INNER JOIN mytest t2
ON t1.id <> t2.id
AND t1.code = t2.code
AND t1.sequence_number = t2.sequence_number
GROUP BY t1.code, 
    t1.sequence_number
    ORDER BY ID