选择序列号的SQL查询
在SQL server中,我想根据序列号选择行。例如,我的数据如下:
ID RowNos
A 1
B 2
X NULL
C 4
D 5
Y NULL
E 7
F 8
G 9
H 11
I 13
查询应返回
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
我无意启动此查询。否则我也会发布我的试用版。
答案 0 :(得分: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)
输出:
---- ----
A B
C D
E G
答案 1 :(得分:0)
选择它们的顺序应该是这样的:
SELECT * FROM table_name WHERE RowNos IS NOT NULL ORDER BY RowNos ASC;