2011-07-06 63 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