gpt4 book ai didi

SQL Server 如何检索两个数字之间的所有数字

转载 作者:行者123 更新时间:2023-12-02 15:16:56 32 4
gpt4 key购买 nike

我有 4 列 - 代码、金额、开始、结束。我想在开始和结束列中获取介于两者之间的金额,并将它们更改为包含所有结果的一列。关于如何实现这一目标的任何建议?谢谢。

Current Results:
Code Amount Start End
1 5000 2015 2016
2 5000 2014 2016
3 20000 2012 2016

Desired Results:
Code Amount StartEnd
1 5000 2015
1 5000 2016
2 5000 2014
2 5000 2015
2 5000 2016
3 20000 2012
3 20000 2013
3 20000 2014
3 20000 2015
3 20000 2016

最佳答案

您可以使用递归 cte 生成最小开始和最大结束之间的所有数字,并连接生成的数字。

with cte as (select min(start) col,max(end) mx from tablename
union all
select col+1,mx from cte where col < mx)
select t.code,t.amount,c.col
from cte c
join tablename t on c.col between t.start and t.end

或者更简单的说

with cte as (select id,amount,start startend,end from tablename
union all
select id,amount,start+1,end from cte where start<end)
select id,amount,startend
from cte
order by 1,3

关于SQL Server 如何检索两个数字之间的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39778951/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com