在SQL SERVER 2005数据库中,请假设我们有一个名为RUNNING_COLA_IS_AFRICA的表。
此表有一个名为RUNNING_ID的唯一varchar(50)字段。
此表中有100万条记录。
我想编写一个查询,按RUNNING_ID ASC排序,并声明范围为50,产生类似于以下内容的输出:
RUNNING_ID_START RUNNING_ID_END
000000 000103
000104 000767
000892 001492
001576 011222
012345 013579
这意味着:
a) The number of the records between 000000 and 000103 is 50;
b) The number of the records between 000104 and 000767 is 50;
c) The number of the records between 000892 and 001492 is 50;
d) The number of the records between 001576 and 011222 is 50;
e) The number of the records between 012345 and 013579 is <= 50.
当然,min(RUNNING_ID)= 000000和max(RUNNING_ID)= 013579,因为它们是由RUNNING_ID ASC排序的。
我如何在SQL SERVER 2005中实现这一目标?
提前感谢您的帮助。
答案 0 :(得分:2)
WITH
sequenced
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY running_id) - 1 AS sequence_id,
*
FROM
RUNNING_COLA_IS_AFRICA
)
SELECT
sequence_id / 50 AS group_id,
MIN(running_id) AS running_id_first,
MAX(running_id) AS running_id_last,
COUNT(*) AS size_of_group
FROM
sequenced
GROUP BY
sequence_id / 50