2

在使用此表的 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)存在多个具有相同序列号的记录的行。我想要代码和序列号的每个唯一组合的所有最高 ID。

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

我该怎么做呢?

4

3 回答 3

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中的演示

于 2013-05-30T11:42:52.620 回答
1

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

于 2013-05-30T11:39:49.057 回答
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
于 2013-05-30T12:03:13.527 回答