考虑到向我们提供帐户ID列表的情况(例如带有account_id
字段(整数(的表(,其帐户号如下所示:
account_id
1001
1002
1003
1008
1009
1010
1011
1050
1051
我正在尝试创建查询,该查询将此列表转换为一个范围。
因此,范围将由连续的帐号序列组成,例如,帐户 ID 从 1001 到 1003 连续,然后是 1008 到 1011,然后是 1050 到 1051。
我正在尝试获得以下输出:
account_from account_to
1001 1003
1008 1011
1050 1051
我被困在这个上面,不知道如何获得所需的结果。这是小提琴。
这是一个经典的 Gaps-and-Islands,可以通过 Row_Number(( 轻松解决
查看子查询的结果以更好地了解方法。
Select account_from = min([account_id])
,account_to = max([account_id])
From (
Select *
,Grp = [account_id] - row_number() over (Order by [account_id])
From YourTable
) A
Group By Grp
返回
account_from account_to
1001 1003
1008 1011
1050 1051
您可以尝试以下查询:
Select
min(account_id) as account_from,
max(account_id) as account_to
from
(
select
account_id,
(account_id - row_number() over (Order by account_id)) as acc
from test
) new
Group By acc