我的数字范围是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查询中如何实现这一点吗?
尝试这个:
;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。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。