运行多个查询,每个查询选择每个相应的第N行?

时间:2015-05-22 16:18:16

标签: sql-server modulo sql-server-2014

`与#34; Selecting every nth row from SQL Server 2008 query result where table does not have row id column"相关,我知道执行以下操作会选择每隔4行。

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

但我想要做的是运行4个单独的查询,分别选择从1,2,3和4开始的第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

???

2 个答案:

答案 0 :(得分:1)

在SQL 2008 SQL Fiddle

上测试它

表格定义

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的结果

enter image description here

答案 1 :(得分:0)

我想通了

给出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