How to sum for a parent/child relationship in MS Access

家住魔仙堡 提交于 2020-01-16 20:06:28

问题


I have a number of Matters which are in a parent/child relationship. Each has a pointer to their parent matter, or null if they are the parent. Each matter can have a payment made, but all payments in a parent/child relationship are shared between both parent and child. A simplified version of my tables is:

Matter

|  ID       |   Value   | ParentID   |
--------------------------------------
|      1    |    200    |      0     |
|      2    |    200    |      1     |
|      3    |    300    |      0     |
|      4    |    200    |      1     |
|      5    |    800    |      0     |

Payment

|  ID       |   Value   | MatterID   |
--------------------------------------
|      1    |    100    |      1     |
|      2    |     50    |      4     |
|      3    |     20    |      3     |

Note that Matter values are inherited by children (in reality it's just a reference)

I would like to query:

  • The remaining amount on every matter = ([Value] - Sum([All Payments in Parent/Child Relationship))
  • A view of all parent matters, which incorporates the sum of all payments in parent/child relationship.

I am thinking of having a join query showing for each Payment which ParentMatter they apply to, but that will not help me when looking from the child view?

The expected results are:

1. Query only parent matters 
|  ID       |   Value   | TotalRcvd  |
--------------------------------------
|      1    |    200    |    150     |
|      3    |    300    |     20     |
|      5    |    800    |      0     |

2. Query all matters
|  ID       |   Value   | TotalRcvd  |
--------------------------------------
|      1    |    200    |    150     |
|      2    |    200    |    150     |
|      3    |    300    |     20     |
|      4    |    200    |    150     |
|      5    |    800    |      0     |

Where [TotalRcvd] is the sum of all payments that appply to that matter. For example, matter 1 is the parent matter of matters 2 and 4 (ParentID reference in Matter table). Any payments recorded against matters 1, 2 or 4 will go towards the TotalRcvd for each of them. Therefore they each have a total received [TotalRcvd] of 150.

Any help appreciated.

来源:https://stackoverflow.com/questions/29958047/how-to-sum-for-a-parent-child-relationship-in-ms-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!