我想多次选择一些行,具体取决于列的值。
来源表
Article | Count
===============
A | 1
B | 4
C | 2
通缉结果
Article
===============
A
B
B
B
B
C
C
请提供任何提示或样品?
答案 0 :(得分:4)
您可以使用:
SELECT m.Article
FROM mytable m
CROSS APPLY (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS s(n)
WHERE s.n <= m.[Count];
的 LiveDemo
强>
注意:CROSS APLLY
包含任何计数表。这里的值最多为10。
相关:What is the best way to create and populate a numbers table?
答案 1 :(得分:1)
您还可以使用递归CTE,它与数字&gt;一起使用。 10(这里最多1000):
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)
数字表肯定是最好的选择。
http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2
答案 2 :(得分:0)
请检查以下SQL脚本 在执行SELECT语句之前,请注意我使用了一个用于模拟数字表的用户函数 您可以在参考教程
中找到numbers table in SQL Server的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
答案 3 :(得分:0)
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
答案 4 :(得分:0)
可以使用简单的 WHILE LOOP
获取输出 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 =@max)
SET @Check =(SELECT [Count] FROM @table WHERE ID =@max)
WHILE (@Cnt2 > 0)
BEGIN
INSERT INTO @temp
SELECT Article FROM @table WHERE [Count] =@Check
SET @Cnt2 = @Cnt2 -1
END
END
SELECT * FROM @temp