2011-07-06 61 views
2

我有一個映射表:遞歸查詢來獲取孩子及其孫子

Code  Parent_code Position 
-------------------------------- 
H1  Null   Root 
H11  H1   Parent 
H111  H11   Parent 
H1111 H111   Leaf 
H1112 H111   Leaf 

存儲量爲葉級代碼

Code Amount 
------------- 
H1111 100 
H1112 200 

即量存儲在只有葉位

還有一個表

我想寫一個查詢,通過這個查詢,葉級別的數據將滾動到它的父項並最終到達其根。

輸出將類似於下面

Code Amount 
------------- 
H1  300 
H11 300 
H111 300 
H1111 100 
H1112 200 

另外,如果我選擇H1是根,然後輸出應該是它的子女和孫輩的。 同樣,如果我選擇H11我應該得到輸出爲H111和H111的孩子

+0

你能上傳一個小的SQL語句來創建一個表並加載一些示例數據嗎?這是很難讀取您的文本語句 – Nat

+0

可能重複的[SQL Server遞歸查詢](http://stackoverflow.com/questions/3916597/sql-server-recursive-query) –

+0

不是重複的,因爲這個問題需要代碼總和得到的金額。足以區分查詢的怪癖 – Nat

回答

1

遞歸公用表表達式應​​該能夠給你你需要的數據。這個網站上的一個很好的問題/答案是here

一個簡單的例子,可以幫助你是這樣的:

create table #Code 
(
Code varchar(20), 
Parent_Code varchar(20) 
) 
go 
insert into #Code (Code, Parent_Code) 
select 'H1', null 
union 
select 'H11', 'H1' 
union 
select 'H111', 'H11' 
union 
select 'H1111', 'H111' 
union 
select 'H1112', 'H111' 
union 
select 'H12', 'H1' 
union 
select 'H121', 'H12' 
go 
create table #CodeAmount 
(
Code varchar(20), 
Amount decimal 
) 
go 
insert into #CodeAmount (Code, Amount) 
select 'H1111', 100 
union 
select 'H1112', 200 
union 
select 'H121', 50 

go 

with CodeAmountRollup(Code, Parent_Code, Amount) 
as 
(
    select c.Code, c.Parent_Code, ISNULL(ca.Amount, 0) as Amount from #Code c inner join #CodeAmount ca on c.Code = ca.Code 
    union all 
    select c.Code, c.Parent_Code, Amount as Amount from #Code c inner join CodeAmountRollup car on c.Code = car.Parent_Code  
) 
--select * from CodeAmountRollup 
select Code, sum(Amount) as Amount from CodeAmountRollup group by Code 
0

下面是一些SQL我最近寫了一個類似的場景,在這裏我需要返回所有持牌人的例子,被許可人的水平排列。希望這可以解釋這個概念。

WITH LicenseeEntity (iLicenseeId, vcLicenseeName, vcTradingName,iLicenseeType,iLicenseeStatus, iOwnerLicenseeId, Level) 
    AS 
    (
     -- Anchor Licensee definition 
     SELECT l.iLicenseeId, l.vcLicenseeName, 
       l.vcTradingName,l.iLicenseeType,l.iLicenseeStatus, 
       l.iOwnerLicenseeId, 1 AS Level 
     FROM Licensee (nolock) AS l 
     WHERE iOwnerLicenseeId IS NULL 

     UNION ALL 
     SELECT l.iLicenseeId, l.vcLicenseeName, 
       l.vcTradingName,l.iLicenseeType,l.iLicenseeStatus, 
       l.iOwnerLicenseeId, 1 AS Level + 1 
     FROM Licensee (nolock) AS l 
     INNER JOIN LicenseeEntity AS le ON l.iOwnerLicenseeId = le.iLicenseeId 
    ) 

    SELECT * FROM LicenseeEntity le