ajc*_*101 2 sql sql-server sql-server-2008
我有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
Run Code Online (Sandbox Code Playgroud)
您可以使用递归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
Run Code Online (Sandbox Code Playgroud)
或者更简单
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
Run Code Online (Sandbox Code Playgroud)