需要根据列中的值生成n行 [英] Need to generate n rows based on a value in a column
本文介绍了需要根据列中的值生成n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表
ID | QUANTITY
------------
1 | 3
2 | 2
我需要的是
ID | Ref No.
------------
1 | MyRef1
1 | MyRef2
1 | MyRef3
2 | AnotherRef1
2 | AnotherRef2
即我需要使用与 A 中的数量相同的行数生成表 B,并带有升序的参考编号.在每一行.
i.e. I need to generate Table B with the same number of rows as the quantity in A with an ascending ref no. on each row.
我可以使用游标或 UDF 来实现,但有没有更优雅的解决方案?
I can do it with cursors or UDFs but is there a more graceful solution?
推荐答案
我会假设
- MyRef 等是 TableA 中的一列
- 您有一个数字表
类似于:
SELECT * INTO #TableA
FROM
(
SELECT 1 AS ID, 3 AS QUANTITY, 'MyRef' AS refColumn
UNION ALL
SELECT 2, 2, 'AnotherRef'
) T
;WITH Nbrs ( Number ) AS (
SELECT 1 UNION ALL
SELECT 1 + Number FROM Nbrs WHERE Number < 99
)
SELECT
A.ID, A.refColumn + CAST(N.Number AS varchar(10))
FROM
#TableA A
JOIN
Nbrs N ON N.Number <= A.QUANTITY
这篇关于需要根据列中的值生成n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文