SELECT语句中的行重复

时间:2018-06-22 12:17:36

标签: sql sql-server

我正尽力避免使用游标-数据量确实很大。表格如下:

|Data| Multiplier|
-----------------|
|A   | 2         |
|B   | 3         |
|C   | 0         |

我需要通过以下方式从其中获取数据:

|Data| Multiplier|
-----------------|
|A   | 2         |
|A   | 2         |
|B   | 3         |
|B   | 3         |
|B   | 3         |

使该行显示的次数与“乘数”值一样多。 我知道可以在Oracle数据库中使用CONNECT语句,但是我需要在MSSQL中使用它。

4 个答案:

答案 0 :(得分:5)

您需要递归方式:

with t as (
     select data, Multiplier, 1 as seq
     from table
     where Multiplier > 0
     union all
     select data, Multiplier, seq+1
     from t
     where seq < Multiplier
)
select *
from t
option (maxrecursion 0);

答案 1 :(得分:4)

如果数字不是很大,我只使用递归CTE:

with cte as (
      select data, 1 as n, multiplier
      from t
      where multiplier > 0
      union all
      select data 1 + n, multiplier
      from cte
      where n < multiplier
    )
select data, multiplier
from cte;

还有其他方法,也使用数字:

select t.data, t.multiplier
from t join
     (select row_number() over (order by (select null)) as n
      from master..spt_values v
     ) n
     on n.n <= t.multiplier;

答案 2 :(得分:1)

您必须对值进行硬编码,但很干净

declare @t table (data char, multi int);
insert into @t values 
('A', 2),
('B', 3),
('C', 0);
select t.*
from @t t 
join (values (1), (2), (3), (4), (5)) v(valueId) 
on v.valueId <= t.multi

答案 3 :(得分:1)

您还可以使用交叉应用

declare  @t table
(data1 varchar(50),mutli int)

insert into @t

values

('a',2),
('b',3),
('c',0),
('d',5)


select data1,mutli from @t a

cross apply (
select * from (
select ROW_NUMBER() over(order by (select null)) as rn from master..spt_values
)x where a.mutli >= rn
)z