2016-09-07 169 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