2

親子関係(階層モデル)の勘定科目表があります。テーブルには、2 種類の口座管理口座と取引口座があります。

トランザクション アカウントには残高がありますが、子アカウントはありません。

コントロール口座には独自の残高はありませんが、子口座があります。


アカウント ID| タイトル |AccountType|ParentID| バランス
------|----------------|----------|--------|-- -------
 1 | アセット | c | null | null | ヌル
 1-1 | 現在の資産 | c | 1 | ヌル
 1-1-1 | 現金 | t | 1-1 | 1000
 1-1-2 | インベントリ | t | 1-1 | 2000年
 1-2 | 固定資産 | c | 1 | ヌル
 1-2-1 | 家具 | t | 1-2 | 1500
 1-2-2 | 建物 | 建物 | t | 1-2 | 3000

次のような結果セットが必要です:


アカウント ID| タイトル |AccountType|ParentID| バランス
------|----------------|----------|--------|-- -------
 1 | アセット | c | null | null | 7500 -- 流動資産と固定資産の合計
 1-1 | 現在の資産 | c | 1 | 3000 -- 現金と在庫の合計
 1-1-1 | 現金 | t | 1-1 | 1000
 1-1-2 | インベントリ | t | 1-1 | 2000年
 1-2 | 固定資産 | c | 1 | 4500 -- 家具と建物の合計
 1-2-1 | 家具 | t | 1-2 | 1500
 1-2-2 | 建物 | 建物 | t | 1-2 | 3000

トランザクション テーブル


ID |アカウントID|金額
---|---------|------
 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 ステートメント、または関数またはストアド プロシージャ。

どんな助けでも大歓迎です

4

2 に答える 2

0

それを行うには多くの方法がありますが、私はいくつかの更新ステートメントでそれを行いました。データベース構造を提供していないことに注意してください。そのため、2 つのテーブルがあると思います。

create table #accounts (
AccountId int
,Title varchar(60)
,AccountType varchar(10)
,ParentID int
,Balance int
)
create table #transactional_accounts (
Id int
,AccountID int
,Amount int
)

insert into #accounts (AccountId, Title, AccountType,ParentID) values
..............
insert into #transactional_accounts values
........... 

 update #accounts
 set Balance= (select SUM(amount) from #transactional_accounts t2 where t1.AccountId= t2.AccountID  )
from #accounts t1
where AccountType ='t'


update #accounts
set Balance= case when t1.ParentID is not null then (select SUM(t2.Balance) from #accounts t2 where t1.AccountId=t2.ParentID)
          else (select SUM(t2.Balance) from #accounts t2)
          end
from #accounts t1
where AccountType ='c'

select * from #accounts
于 2013-11-01T09:38:04.187 に答える