Sto*_*ude 0 sql t-sql sql-server
我可以使用查询的一些帮助来扩展我正在使用的CSV,但我不知道处理查询的最佳方法.我的数据如下:
ID-Begin | ID-End | Color | Dwelling
-------------------------------------
79000 | 79999 | Red | Condo
82100 | 82600 | Blue | House
etc
Run Code Online (Sandbox Code Playgroud)
我需要在起始ID和结束ID之间生成一个范围,然后复制该范围的颜色和居住条目.这是我希望实现的目标:
ID | Color | Dwelling
------------------------
79000 | Red | Condo
79001 | Red | Condo
79002 | Red | Condo
.....
79999 | Red | Condo
82100 | Blue | House
82101 | Blue | House
.....
82600 | Blue | House
Run Code Online (Sandbox Code Playgroud)
我已经看到其他方法允许我生成单个数字范围,但没有任何方法可以从表中的列中提取开始和结束数字.
无论如何帮助非常感谢!!
风暴
小智 5
试试这个:
declare @content table ([ID-Begin] int,[ID-End] int,Color char(20),Dwelling char(20))
insert into @content values(79000,79999,'Red' ,'Condo')
insert into @content values(82100,82600,'Blue','House')
;with cte as (
select [ID-Begin] ,[ID-End] ,Color,Dwelling
from @content
union all
select [ID-Begin]+1,[ID-End],Color,Dwelling
from cte
where [ID-Begin]+1<=[ID-End]
)
select [Id-Begin],Color,Dwelling from cte order by [ID-Begin]
option (maxrecursion 10000)
Run Code Online (Sandbox Code Playgroud)
你可以用这样的递归 CTE 来做到这一点
;WITH temp AS
(
SELECT 1 AS ID
UNION ALL
SELECT t.ID + 1 FROM temp t
WHERE t.ID < 100000
) -- return table with id from 1 to 100000
SELECT t.ID, y.Color, y.Dwelling
FROM YourTable y
INNER JOIN temp t ON t.ID BETWEEN y.IdBegin AND y.IdEnd
OPTION (MAXRECURSION 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2750 次 |
| 最近记录: |