Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

tsql - Return row of every n'th record

How can I return every nth record from a sub query based on a numerical parameter that I supply?

For example, I may have the following query:

SELECT
   Id,
   Key
FROM DataTable
WHERE CustomerId = 1234
ORDER BY Key

e.g.

The subquery result may look like the following:

Row Id   Key
1   1    A3231
2   43   C1212
3   243  E1232
4   765  G1232
5   2432 E2325
...
90  3193 F2312

If I pass in the number 30, and the sub query result set contained 90 records, I would recieve the 30th, 60th, and 90th row.

If I pass in the number 40, and the result set contained 90 records, I would recieve the 40th and 80th row.

As a side note, for background information, this is being used to capture the key/id of every nth record for a paging control.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is where ROW_NUMBER can help. It requires an order-by clause but this is okay because an order-by is present (and required to guarantee a particular order).

SELECT t.id, t.key
FROM
(
    SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
    FROM datatable
) AS t
WHERE t.rownum % 30 = 0    -- or % 40 etc
ORDER BY t.key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...