1

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

2 回答 2

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

这给出了结果:

| STOCKCODE |   BARCODE |
-------------------------
|      DESK | 568123122 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
| GUITAR101 | 456812313 |
|      LAMP | 845646962 |
|      LAMP | 845646962 |
于 2013-02-12T02:05:00.143 回答
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。)

于 2013-02-12T01:55:59.030 回答