我有一個父子關係(層次模型)的帳戶圖表表。 該表包含兩種類型的賬戶控制賬戶和交易賬戶。在各自的父記錄中選擇子記錄的總數
交易賬戶有餘額,但沒有任何子賬戶。
控制帳戶沒有自己的餘額,但他們帶有子帳戶。
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
任何選擇語句如果可能 或函數或存儲過程。
任何幫助將不勝感激
您需要顯示您正在從中獲取數據的其他表的結構以及如何計算適當的值。 – Harrison
這種類型的查詢面臨的挑戰之一是它是遞歸的,一般來說SQL並不擅長。但是,由於您在SQL Server中運行,請查看CTE(通用表格表達式)。 – asantaballa