我有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,accountto为accountnumber
你能帮我怎么做吗?
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)
使用您提供的数据,此查询会显示您指定的输出。它被硬编码为4级,所以如果你需要更动态的东西,那么就需要进一步思考。
我还假设221分支没有出现的原因是因为它需要在父ID和子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