如何在我的选择输出中创建一个包含序列和种子的列

时间:2013-05-20 10:55:12

标签: sql sql-server-2012

我有一个像这样的选择

SELECT 
TOP (5)
 ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
 ,S.SubscribeNumber AS SN
FROM billing.Subscribe AS S
ORDER BY S.Id

有输出像这样

RowNumber            SN
-------------------- --------
1                    01100017
2                    01100025
3                    01100033
4                    01100041
5                    01100050
(5 row(s) affected)

我有另一个选择像这样

 SELECT 
 ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
 ,S.SubscribeNumber AS SN
FROM billing.Subscribe AS S
 ORDER BY S.Id
 OFFSET (5) ROWS
FETCH NEXT (5) ROWS ONLY;

有输出像这样

RowNumber            SN
-------------------- --------
6                    01100068
7                    01100076
8                    01100084
9                    01100092
10                   01100106
(5 row(s) affected)

我如何能联合所有两个选择并得到这样的结果

RowNumber            Sn
-------------------- --------
1                    01100017
6                    01100068
2                    01100025
7                    01100076
3                    01100033
8                    01100084
4                    01100041
9                    01100092
5                    01100050
10                   01100106
(10 row(s) affected)

2 个答案:

答案 0 :(得分:4)

SELECT *
FROM
    (
    SELECT TOP (5)
        ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
        ,S.SubscribeNumber AS SN
    FROM billing.Subscribe AS S
    UNION ALL
    SELECT TOP 5
        ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
         ,S.SubscribeNumber AS SN
    FROM billing.Subscribe AS S
    ORDER BY S.Id
    OFFSET (5) ROWS
    FETCH NEXT (5) ROWS ONLY
    ) X
ORDER BY (RowNumber-1)%5, RowNumber;

编辑:现在可以使用

答案 1 :(得分:2)

请尝试:

SELECT * FROM(
    SELECT 
    TOP (5)
     ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
     ,S.SubscribeNumber AS SN
    FROM billing.Subscribe AS S
    ORDER BY S.Id
    UNION ALL
    SELECT 
     ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
     ,S.SubscribeNumber AS SN
    FROM billing.Subscribe AS S
     ORDER BY S.Id
     OFFSET (5) ROWS
    FETCH NEXT (5) ROWS ONLY
)x
ORDER BY CASE WHEN RowNumber-5<=0 THEN RowNumber ELSE RowNumber-5 END, RowNumber

相反,这将解决您的问题我想

SELECT * FROM(
    SELECT 
    TOP (10)
     ROW_NUMBER() OVER(ORDER By S.Id) AS RowNumber 
     ,S.SubscribeNumber AS SN
    FROM billing.Subscribe AS S
    ORDER BY S.Id
)x
ORDER BY CASE WHEN RowNumber-5<=0 THEN RowNumber ELSE RowNumber-5 END, RowNumber