2016-09-07 175 views
-1

我有3个表格:结构,帐户范围和accountvalueUSD。从父母和孩子ID的表结构的层次,我想创建这样一个层次结构:如何创建此层次结构

Level 1...Level 2...Level 3...Level 4....account...valueusd 
111  112 113  114  100  1000 
111  112  113  114  101  2000 

将与表考虑范围之内与主要的表结构链接:financialitem

与表的表acountrange链接帐号值与关键字:accountfrom和accounto帐号

您可以请帮助我如何做到这一点?

CREATE TABLE [dbo].[structure](
    [Financialitem] [nvarchar](3) NULL, 
    [ID] [int] NULL, 
    [ParentID] [int] NULL, 
    [ChildID] [int] NULL, 
    [NextID] [int] NULL, 
    [Level] [int] NULL 
) ON [PRIMARY] 
INSERT INTO [dbo].[structure] 
VALUES 
(111,1,null,2,null,1), 
(112,2,1,3,null,2), 
(113,3,2,4,null,3), 
(114,4,3,null,null,4), 
(221,5,2,6,null,3), 
(222,6,5,null,7,4), 
(223,7,5,null,null,4) 

    CREATE TABLE [dbo].[accountrange](
    [Financialitem] [nvarchar](3) NULL, 
    [Accountfrom] [int] NULL, 
    [Accountto] [int] NULL 
) ON [PRIMARY] 
INSERT INTO [dbo].[accountrange] 
VALUES 
(114,100,105), 
(222,200,205), 
(223,300,305) 


    CREATE TABLE [dbo].[accountvalue](
    [accountnumber] [int] NULL, 
    [valuesUSD] [int] NULL, 
) ON [PRIMARY] 
INSERT INTO [dbo].[accountvalue] 
VALUES 
(100,1000), 
(101,2000), 
(301,1500), 
(201,1400) 
+0

你能说明你正在使用什么系统语言或符号或询问。 –

+0

感谢Brian,我正在使用T SQL。 – phalondon

回答

0

使用您提供的数据,该查询将提供您指定的输出。它很难编码到4个级别,所以如果你需要更多的动态,那么就需要进一步考虑。

我也假定221分支没有出现的原因是因为它需要匹配父和子ID列。

select L1.Financialitem as [Level 1] 
    , L2.Financialitem as [Level 2] 
    , L3.Financialitem as [Level 3] 
    , ar.Financialitem as [Level 4] 
    , av.accountnumber, av.valuesUSD 
from accountrange ar 
inner join accountvalue av on av.accountnumber between ar.Accountfrom and ar.Accountto 
inner join structure as L4 on L4.Financialitem = ar.Financialitem 
inner join structure as L3 on L3.ID = L4.ParentID and L3.ChildID = L4.ID 
inner join structure as L2 on L2.ID = L3.ParentID and L2.ChildID = L3.ID 
inner join structure as L1 on L1.ID = L2.ParentID and L1.ChildID = L2.ID