2

In SQL Server 2008 R2 using this table:

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

This query:

SELECT id, code, sequence_number
  FROM mytable

returns this data:

 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

How do I SELECT just these rows:

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

These are the the MAX(id) rows where there is more than one record with the same sequence_number. I want all the highest ids for each unique combination of code and sequence_number.

So, in effect I want to select just the "duplicate" sequence_number records.

How do I do this?

1
  • have you tried my ans? Commented May 30, 2013 at 12:10

3 Answers 3

2

Try this :-

 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

Demo in SQL FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

1

use this

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.