1

在 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 中实现这一点?

预先感谢您的帮助。

4

1 回答 1

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
于 2012-10-19T15:44:04.090 回答