我想在 SQL 中按数量执行简单的拆分。
我有如下:
表名:产品
product quantity
======= ========
Car 2
Bike 1
结果:
Car
Car
Bike
谢谢!
我想在 SQL 中按数量执行简单的拆分。
我有如下:
表名:产品
product quantity
======= ========
Car 2
Bike 1
结果:
Car
Car
Bike
谢谢!
一种解决方案是加入一个数字表。这可以重复行quantity
时间。在 T-SQL 中,可以使用递归 CTE 生成数字列表:
; with Numbers as
(
select max(quantity) as nr
from YourTable
union all
select nr - 1
from Numbers
where nr > 1
)
select yt.product
from YourTable yt
join Numbers nr
on nr.nr <= yt.quantity
option (maxrecursion 0)
这是一个非 CTE 答案,说明为什么应该使用 CTE :)
主表
DECLARE @table TABLE
(
ID INT IDENTITY,
Product VARCHAR(20),
Quantity INT
)
出表
DECLARE @outtable TABLE
(
ID INT IDENTITY,
Product VARCHAR(20)
)
测试数据
INSERT INTO @table
(
Product,
Quantity
)
SELECT 'Car',
2
UNION ALL
SELECT 'Bike',
1
主要查询
DECLARE @counter INT,
@maxcounter INT,
@curproduct INT
SELECT TOP 1
@curproduct = id
FROM @table
WHILE EXISTS ( SELECT TOP 1
1
FROM @table
WHERE ID >= @curproduct )
BEGIN
SELECT @counter = 1,
@maxcounter = quantity
FROM @table
WHERE ID = @curproduct
WHILE @counter <= @maxcounter
BEGIN
INSERT INTO @outtable
(
Product
)
SELECT product
FROM @table
WHERE id = @curproduct
SET @counter = @counter + 1
END
SET @curproduct = @curproduct + 1
END
最后
SELECT *
FROM @outtable