【问题标题】:SQL list into a range outcomeSQL 列表成范围结果
【发布时间】:2017-06-19 12:46:24
【问题描述】:

考虑一种情况,我们提供了一个帐户 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

我对此感到困惑,不知道如何获得所需的结果。这是fiddle

【问题讨论】:

    标签: sql sql-server sql-server-2008 gaps-and-islands


    【解决方案1】:

    这是一个经典的间隙和岛屿,可以通过 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
    

    【讨论】:

      【解决方案2】:

      你可以试试下面的查询:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 1970-01-01
        相关资源
        最近更新 更多