2016-05-18 15 views
0

列の値に応じて、いくつかの行を複数回選択したいとします。selectのSQL乗算行

ソーステーブル

Article | Count 
=============== 
A  | 1 
B  | 4 
C  | 2 

募集結果

Article 
=============== 
A 
B 
B 
B 
B 
C 
C 

任意のヒントやサンプルを、してください?

答えて

1

numbers table in SQL Serverのコードあなたはまた、(ここでは1000年まで)の数字> 10で動作する再帰CTEを使用することができます。

With NumberSequence(Number) as 
(
    Select 0 as Number 
     union all 
    Select Number + 1 
     from NumberSequence 
    where Number BETWEEN 0 AND 1000 
) 
SELECT Article 
FROM ArticleCounts 
CROSS APPLY NumberSequence 
WHERE Number BETWEEN 1 AND [Count] 
ORDER BY Article 
Option (MaxRecursion 0) 

Demo

数テーブルは確かに最良の選択肢となります。

http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2

0

、SELECTステートメントを実行する前に、次のSQLスクリプト をチェックし、私はあなたがSQLを見つけることができる番号テーブル をシミュレートするために使用されるユーザ機能を利用していることに注意してください呼ばチュートリアル

----create table myTempTbl (Article varchar(10), Count int) 
--insert into myTempTbl select 'A',1 
--insert into myTempTbl select 'B',4 
--insert into myTempTbl select 'C',2 

select t.* 
from myTempTbl t 
cross apply dbo.NumbersTable(1,100,1) n 
where n.i <= t.Count 
order by t.Article 
+0

なぜANSI JOIN構文を使用していないを使用して出力を得ることができますか? – Squirrel

+0

SELECTを編集し、CROSS APPLY :)を追加しました。 – Eralper

0

1以上CTE

with cte_t as (
    select c as c, 1 as i 
     from mytable 
     group by c 
    union all 
    select t.c, ctet.i + 1 
     from mytable t 
      join cte_t ctet 
       on ctet.c = t.c 
        and ctet.i < t.i 
) 
select cte_t.c 
    from cte_t 
    order by cte_t.c 
0

は、単純なwhileループ

 DECLARE @table TABLE 
     (ID int ,Article varchar(5),[Count] int) 

     INSERT INTO @table 
     (ID,Article,Count) 
     VALUES 
     (1,'A',1),(2,'B',4),(3,'C',2) 

     DECLARE @temp TABLE 
     (Article varchar(5)) 

     DECLARE @Cnt1 INT 
     DECLARE @Cnt2 INT 
     DECLARE @Check INT 
     DECLARE @max INT 
     SET @max =0 
     SET @Cnt1 = (SELECT Count(Article) FROM @table) 

     WHILE (@max < @Cnt1) 
     BEGIN 
      SET @max = @max +1 
      SET @Cnt2 = (SELECT [Count] FROM @table WHERE ID [email protected]) 
      SET @Check =(SELECT [Count] FROM @table WHERE ID [email protected]) 
      WHILE (@Cnt2 > 0) 
      BEGIN 
       INSERT INTO @temp 
       SELECT Article FROM @table WHERE [Count] [email protected] 
       SET @Cnt2 = @Cnt2 -1 
      END 
     END 
     SELECT * FROM @temp