2

SQL Query for Select Sequence Numbers

In SQL server, I want to select rows based on sequence numbers. For example I am having data as below:

ID RowNos
A  1
B  2
X  NULL
C  4
D  5
Y  NULL
E  7
F  8
G  9
H  11
I  13

Query Should return

ID NextID 
A  B      -- Since RowNos 1,2 is in sequence
C  D      -- Since RowNos 4,5 is in sequence
E  G      -- Since RowNos 7,8,9 is in sequence

I don't have idea to start this query. Otherwise I'll post my trial too.

4
  • 1
    Your example seems somewhat unclear to me. Are you looking at sequence of ID or RowNos - if the latter is it guaranteed that they are unique and will be sequential except for the intervening NULL? What version of SQL Server? Commented Jul 18, 2016 at 10:49
  • @MartinSmith, I want to retrieve the ID and Next ID based on the sequence. For example, 1,2 is the sequence because 3 is missing So A(1) Is the ID and B(2) is the Next ID. Commented Jul 18, 2016 at 10:53
  • 1
    Is RowNos unique for not null values? What version of SQL Server? Commented Jul 18, 2016 at 10:57
  • @MartinSmith Yes Its unique.. Commented Jul 18, 2016 at 12:01

2 Answers 2

3
DECLARE @t TABLE (ID CHAR(1), RowNos INT)
INSERT INTO @t
VALUES
    ('A', 1), ('B', 2), ('X', NULL),
    ('C', 4), ('D', 5), ('Y', NULL),
    ('E', 7), ('F', 8), ('G', 9),
    ('H', 11), ('I', 13)

SELECT MIN(ID), MAX(ID)
FROM (
    SELECT *, rn = ROW_NUMBER() OVER (ORDER BY RowNos)
    FROM @t
) t
WHERE RowNos IS NOT NULL
GROUP BY RowNos - rn
HAVING MIN(ID) != MAX(ID)

Output:

---- ----
A    B
C    D
E    G
Sign up to request clarification or add additional context in comments.

Comments

0

to select them ordered should be something like:

SELECT * FROM table_name WHERE RowNos IS NOT NULL ORDER BY RowNos ASC;

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.