2013-02-12 57 views

回答

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 | 
+0

真棒,非常感謝我申請這個到數據庫,它的工作完美:) – 2013-02-13 00:18:14

+0

@TanyaHelenFulton很高興它的工作。 – Taryn 2013-02-13 10:22:54

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)

相關問題