在这个TSQL CTE中,我试图建立一个递归的发票列表,从父版本开始,每个发票的版本为1。
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'会给你:
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
感谢您一看!
答案 0 :(得分:3)
你需要有一个递归CTE,在每个递归调用中需要递减ver
列
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 INVOICE, VER from myList
UNION ALL
SELECT INVOICE, VER-1 FROM newList
WHERE VER >1
)
SELECT * FROM newList order by INVOICE, VER desc