如何创建一个基于另一个字段中的数量将一行变成多行的视图?
问题描述:
我与微软SQL工作如何创建一个基于另一个字段中的数量将一行变成多行的视图?
我有一个表CR_INVLINES显示类似下面
STOCKCODE QTY BARCODE
GUITAR101 3 456812313
DESK 1 568123122
LAMP 2 845646962
我需要我的观点返回是像下面的数量的倍数线:
STOCKCODE BARCODE
GUITAR101 456812313
GUITAR101 456812313
GUITAR101 456812313
DESK 568123122
LAMP 845646962
LAMP 845646962
答
您可以使用递归CTE得到结果:
;WITH CTE AS
(
SELECT *
FROM CR_INVLINES
UNION ALL
SELECT stockcode, qty-1, BARCODE
FROM CTE
WHERE qty-1 >= 1
)
SELECT STOCKCODE, Barcode
FROM CTE
order by stockcode
OPTION(MAXRECURSION 0);
这给出结果:
| STOCKCODE | BARCODE |
-------------------------
| DESK | 568123122 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
| LAMP | 845646962 |
| LAMP | 845646962 |
答
那么,为此,你需要一个数字表。这里是一个快速和简单的解决方案,在许多情况下工作:
with numbers as (
select row_number() over (order by (select null)) as num
)
select il.stockcode, barcode
from CR_INVLINES il join
numbers n
on il.qty <= n.num
更正式的回答是这样的:
with digits as (
select 0 as d union all select 1 union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
),
numbers as (
select d1.d*100+d2.d*10+d3.d
from digits d1 cross join digits d2 cross join digits d3
)
select il.stockcode, barcode
from CR_INVLINES il join
numbers n
on il.qty < n.num
(注意<=
改为<
因为组数字现在有0)
真棒,非常感谢我申请这个到数据库,它的工作完美:) – 2013-02-13 00:18:14
@TanyaHelenFulton很高兴它的工作。 – Taryn 2013-02-13 10:22:54