我有一个具有父子关系的会计科目表(层次结构模型)。 该表包含两种类型的帐户:控制帐户和交易帐户。
交易账户有余额,但不带有任何子账户。
控制账户没有自己的余额,但有子账户。
AccountID| Title |AccountType|ParentID| Balance ---------|----------------|-----------|--------|--------- 1 | Assets | c | null | null 1-1 | Current Assets | c | 1 | null 1-1-1 | Cash | t | 1-1 | 1000 1-1-2 | Inventory | t | 1-1 | 2000 1-2 | Fixed Assets | c | 1 | null 1-2-1 | Furniture | t | 1-2 | 1500 1-2-2 | Building | t | 1-2 | 3000
我需要一个像这样的结果集:
AccountID| Title |AccountType|ParentID| Balance ---------|----------------|-----------|--------|--------- 1 | Assets | c | null | 7500 --sum of current and fixed Assets 1-1 | Current Assets | c | 1 | 3000 --sum of cash and inventory 1-1-1 | Cash | t | 1-1 | 1000 1-1-2 | Inventory | t | 1-1 | 2000 1-2 | Fixed Assets | c | 1 | 4500 --sum of furniture and building 1-2-1 | Furniture | t | 1-2 | 1500 1-2-2 | Building | t | 1-2 | 3000
交易表
ID |AccountID|Amount ---|---------|------ 1 | 1-1-1 | 300 2 | 1-1-1 | 700 3 | 1-1-2 | 1500 4 | 1-1-2 | 500 5 | 1-2-1 | 700 6 | 1-2-1 | 800 7 | 1-2-2 | 2000 8 | 1-2-2 | 1000
任何 select 语句(如果可能) 或函数或存储过程。
任何帮助将不胜感激
最佳答案
方法 1(感谢 asantaballa 将我的注意力转移到 CTE)
With TrialBalance(AccountID, ParentID, Balance)
AS
(
Select AccountId, ParentID, Balance From Accounts Where AccountType = 't'
Union All
Select A.AccountId, A.ParentID, T.Balance From Accounts A
Inner Join TrialBalance T On A.AccountId = T.ParentID
)
Select AccountID, SUM(Balance) From TrialBalance Group By AccountID
方法2
Create Function AccountBalance(@AccountID Nvarchar(100))
Returns Float
AS
Begin
Declare @Balance Float
Select @Balance = Balance From Accounts Where AccountID = @AccountID
Select @Balance += Sum(dbo.AccountBalance(AccountID)) From Accounts
Where ParentID = @AccountID
Return @Balance
End
Select AccountID, dbo.AccountBalance(AccountID) From Accounts
以上两种方法都返回所需的结果。
关于sql - 选择各自父记录中的子记录总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19713283/