0
在此TSQL CTE中,我試圖建立一個遞歸的以父版本開始的發票列表,每個發票的版本爲1。CTE遞歸查詢以填充序列
With
myList
AS (Select 10000 as INVOICE, 3 as VER
UNION ALL
Select 20000 as INVOICE, 5 as VER
UNION ALL
Select 30000 as INVOICE, 8 as VER
UNION ALL
Select 40000 as INVOICE, 2 as VER)
,newList (Invoice, Ver)
AS (Select
L1.Invoice
,L1.Ver
from
myList L1
UNION ALL
Select
L2.Invoice
,L2.Ver - 1 Ver
from
myList L2
Join
newList L3
on L2.invoice = L3.Invoice and L2.VER = L3.VER
Where
L2.Ver > = 1)
Select * from newList order by INVOICE, VER desc
上 'myList中' A選擇會給你:
Invoice Ver
10000 3
20000 5
30000 8
40000 2
而我希望達到的目標是:
Invoice Ver
10000 3
10000 2
10000 1
20000 5
20000 4
20000 3
20000 2
20000 1
30000 8
30000 7
30000 6
30000 5
30000 4
30000 3
30000 2
30000 1
40000 2
40000 1
我嘗試了許多變化(當然不是正確的!)但我能做的最好的只是實現第二級...
Invoice Ver
10000 3
10000 2
20000 5
20000 4
30000 8
30000 7
40000 2
40000 1
感謝您的光臨!
哈哈 - 以爲我做你說的正是我需要做的。我想微軟的例子讓我失望了,因爲CTE的兩條腿都引用了錨點查詢。無論如何,做得好! – flaZer 2014-11-03 19:58:27