2017-06-19 46 views
2

考虑在那里我们提供了帐户ID列表的情况下,其具有账户号码:SQL表到一系列成果

account_id 
    1001 
    1002 
    1003 
    1008 
    1009 
    1010 
    1011 
    1050 
    1051 

我试图创建将这个列表翻译成一个范围的查询。

等等一系列将包括账户号码的连续序列,例如,帐户ID是1001年至1003年连续的,那么1008至11年,那么1050〜1051

我试图让下面的输出:

account_from account_to 
    1001   1003 
    1008   1011 
    1050   1051 

我被困在这没有知道如何让结局needed.This是fiddle

回答

4

这是一个经典的差距,和岛屿,可以很容易地通过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 
3

你可以试试下面的查询:

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