如何创建一个视图,根据另一个字段中的数量将一行转换为多行?

时间:2013-02-12 01:50:52

标签: sql sql-server-2008

我正在使用Microsoft 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

2 个答案:

答案 0 :(得分:1)

嗯,为此,你需要一个数字表。这是一个快速简便的解决方案,适用于许多情况:

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。)

答案 1 :(得分:1)

您可以使用递归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);

请参阅SQL Fiddle with Demo

这给出了结果:

| STOCKCODE |   BARCODE |
-------------------------
|      DESK | 568123122 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
|      LAMP | 845646962 |
|      LAMP | 845646962 |