开发者社区> 问答> 正文

在SQL查询中根据给定范围对数字进行拆分

我的数字范围是1 -10。我需要根据给定范围拆分此数字。可用数据如

NumberStart      NumberEnd   Count 
1                     10      10
根据输入集划分范围,

NumberStart     NumberEnd 
2                3 
5                7
因此预期结果集应该是

 NumberStart         NumberEnd     Count
  1                       1         1
  2                       3         2
  4                       4         1
  5                       7         3 
  8                       10        3

有人可以建议在SQL查询中如何实现这一点吗?

展开
收起
祖安文状元 2020-01-03 16:16:00 793 0
1 条回答
写回答
取消 提交回答
  • 尝试这个:

    ;with Ranges as
        (
            select  1   as  NumberStart,
                    10  as  NumberEnd
        ),
        InputSet as 
        (
            select  2   as  NumberStart,
                    3   as  NumberEnd
            union all
            select  5,
                    7
        ),
        cte as
        (
            select  (select min(NumberStart) from Ranges)   as  rn,
                    (select max(NumberEnd) from Ranges)     as  rn_end
            union all
            select  rn+1,
                    t.rn_end
            from    cte t
            where   t.rn < t.rn_end
        )
    select  min(isnull(t2.NumberStart,t1.rn))                                   as  NumberStart,
            coalesce(t2.NumberEnd,v3.NumberEnd-1,v4.NumberEnd)                  as  NumberEnd,
            count(*)                                                            as  Cnt
    from    cte t1
    left join InputSet t2 on t1.rn between t2.NumberStart and t2.NumberEnd
    outer apply (
                    select  min(NumberStart)    as  NumberEnd
                    from    InputSet tt
                    where   tt.NumberStart > t1.rn
                ) v3
    outer apply (
                    select  max(NumberEnd)  as  NumberEnd
                    from    Ranges
                ) v4
    group by coalesce(t2.NumberEnd,v3.NumberEnd-1,v4.NumberEnd)
    order by 1
    option (maxrecursion 32000)
    
    

    但!如果间隔设置不正确,它将不起作用:您必须确保间隔(InputSet)不相交,并且Start小于End。

    2020-01-03 16:16:19
    赞同 展开评论 打赏
问答分类:
SQL
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载