MS SQL如何从表中选择n行,即使表有n - x行

时间:2016-04-28 10:15:56

标签: sql sql-server

我有一张包含以下数据的表格:

  lintOptions {
        abortOnError false
    }

当我想选择5行时,我想获得下一个数据:

ID | Name
---------
1  | John
2  | Alice

有什么想法如何制作这个?

2 个答案:

答案 0 :(得分:2)

适用于n > 1行:

;WITH cte AS (
SELECT *
FROM (VALUES
(1, 'John'),
(2, 'Alice')
) AS t(ID, Name)
)
,res AS (
    SELECT  id,
            name,
            ROW_NUMBER() OVER (partition by id ORDER BY ID) as pid
    FROM cte
    UNION ALL
    SELECT  c.id,
            c.name,
            pid + 1
    FROM res r
    INNER JOIN cte c 
        ON pid = c.id 
)

SELECT TOP 5 
        id,
        name
FROM res

输出:

id          name
----------- -----
1           John
2           Alice
1           John
2           Alice
1           John

(5 row(s) affected)

答案 1 :(得分:2)

-- to create a sample table.
CREATE TABLE table1 (ID BIGINT, NAME VARCHAR(255))
INSERT INTO table1 VALUES (1, 'John'), (2, 'Alice')

-- set number of rows you need
DECLARE @RowsReqd INT = 5  

-- find out the max ID we want to generate 
DECLARE @Limit INT
SELECT @Limit = MAX(ID) FROM table1

-- generate the list
;WITH NumbersList
AS (
    SELECT 1 AS Number, 1 AS ID
    UNION ALL
    SELECT Number + 1, Number % @Limit + 1 FROM NumbersList
    WHERE Number < @RowsReqd    
    )
SELECT T.*
FROM NumbersList NL
INNER JOIN table1 T ON T.ID = NL.ID
ORDER BY NL.Number
OPTION (MAXRECURSION 10000) -- increase this value to generate more numbers

输出:

ID   NAME
1    John
2    Alice
1    John
2    Alice
1    John