我有一个父子关系(层次模型)的帐户图表表。 该表包含两种类型的账户控制账户和交易账户。在各自的父记录中选择子记录的总数
交易账户有余额,但没有任何子账户。
控制帐户没有自己的余额,但他们带有子帐户。
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