2017-05-17 25 views
-1

私は働いているCSVを拡張するためにクエリでいくつかのヘルプを使用することができますが、クエリを処理する最良の方法はわかりません。私のデータは次のようになります。2つの数字の間の数字の範囲を生成

ID-Begin | ID-End | Color | Dwelling 
------------------------------------- 
79000 | 79999 | Red | Condo 
82100 | 82600 | Blue | House 
etc 

は、私が始め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 

私は、私は、単一の番号の範囲が、最初とテーブルの列から数字を終了を引っ張る何を生成することを可能にする他の方法を見てきました:これは私が達成するために願っていますものです。

とにかく助けてくれてありがとう!

ストーム

+0

は、内側には数字のテーブルに参加する使用:あなたは数字のテーブルを持っていたら

は、あなたが必要とするすべては、内部結合を使用することです。 –

答えて

0

をあなたはこの

;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) 
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) 
+0

あなたの答えは私より優れています... +1 – TriV

1

番号またはタリーテーブルを使用
SELECT n.number as ID, t.Color, t.Dwelling 
FROM yourtable t 
     INNER JOIN number_table n ON n.number >= t.ID_Begin 
           AND n.number <= t.ID_End 
1

のように再帰CTEでそれを行うことができます最も簡単な(おそらく最高の)WAこれを行うには、数値表を使用することです。数値表がない場合は、それを作成する方法についてthis Stackoverflow postを読んでください。数字表が何であるかを知りたいのであれば、なぜそれが欲しいのですか?this blog post、Jeff Modenが読んでください。

SELECT Number as Id, 
     Color, 
     Dwelling 
FROM YourTable 
INNER JOIN Numbers ON Number >= [ID-Begin] 
        AND Number <= [ID-End] 
関連する問題