运行 多个查询,每个查询分别选择第 N 行?

Run multiple queries each selecting each respective Nth row?

`与“Selecting every nth row from SQL Server 2008 query result where table does not have row id column”相关,我知道执行以下操作会 select 每 4 行。

SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0

但我想做的是 运行 4 个单独的查询 select 第 4 行分别从 1、2、3 和 4 开始。会像这样吗?

SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0

SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 1

SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 2

SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 3

或者

SELECT ID, Whatever FROM MyTable WHERE ID + 1 % 4 = 0

SELECT ID, Whatever FROM MyTable WHERE ID + 2 % 4 = 0

SELECT ID, Whatever FROM MyTable WHERE ID + 3 % 4 = 0

SELECT ID, Whatever FROM MyTable WHERE ID + 4 % 4 = 0

???

在 SQL 2008 SQL Fiddle

进行测试

Table定义

DROP TABLE [dbo].[testSQL];
CREATE TABLE [dbo].[testSQL](
    [ID] [int] NULL
) ON [PRIMARY]

insert into testSQL values (1);
insert into testSQL values (2);
insert into testSQL values (3);
insert into testSQL values (4);
insert into testSQL values (5);
insert into testSQL values (6);
insert into testSQL values (7);
insert into testSQL values (8);
insert into testSQL values (9);
insert into testSQL values (10);
insert into testSQL values (11);
insert into testSQL values (12);
insert into testSQL values (13);
insert into testSQL values (14);
insert into testSQL values (15);

你只需要创建一个接收@skip作为参数的函数

DECLARE @skip int;
DECLARE @total int;
SET @skip = 2; -- how many row will you skip in your case {0,1,2,3}

SELECT @total = (
    SELECT  count(*)
    FROM testSQL
) - @skip;   -- total rows - number row you want skip

-- here begin the magic
WITH SkipN (ID)  -- skip first N rows
AS
(
    SELECT TOP (@total) * 
    FROM testSQL
    ORDER BY ID DESC -- skip rows will be at the end
)   
, final AS ( -- assign new id
    SELECT ROW_NUMBER() OVER (ORDER BY ID) as new_id, * 
    FROM SkipN
)
SELECT *
FROM final
WHERE new_id % 4 = 0

@skip = 2 的结果

我想通了

给定 20 行和 4 次迭代:

第 1、5、9、13、17 行: SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 1

第 2、6、10、14、18 行:SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 2

第 3、7、11、15、19 行:SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 3

第 4、8、12、16、20 行:SELECT ID, Whatever FROM MyTable WHERE ID % 4 = 0