带有子表的自引用表
我有一个自引用表,其内容如下:
Self-referencing parent table
ID ParentID Name
---------------------
1 John
2 1 Mike
3 2 Erin
4 1 Janie
5 Eric
6 5 Peter
树层次结构应如下所示
- John
- 迈克
- 艾琳
- 珍妮
- 迈克
- 埃里克
- 彼得
还有一个存储父表叶子的子表,如下所示:
ID Sales
3 100
3 100
4 200
4 200
6 300
6 300
6 300
我正在尝试将总和从叶节点向上滚动到层次结构,以便它将返回为..
ID Name Sum
1 John 800
2 Mike 200
3 Erin 200
4 Janie 400
5 Eric 900
6 Peter 900
任何想法如何在sql 2008中实现这个吗?提前致谢。
I have a self-referencing table with content like this:
Self-referencing parent table
ID ParentID Name
---------------------
1 John
2 1 Mike
3 2 Erin
4 1 Janie
5 Eric
6 5 Peter
The tree hierarchy should look like this
- John
- Mike
- Erin
- Janie
- Mike
- Eric
- Peter
And a child table that stores the leaf of parent table that looks like this:
ID Sales
3 100
3 100
4 200
4 200
6 300
6 300
6 300
I'm trying to roll-up the sum from the leaf node up to the hierarchy so it would return as ..
ID Name Sum
1 John 800
2 Mike 200
3 Erin 200
4 Janie 400
5 Eric 900
6 Peter 900
Any ideas how to achieve this in sql 2008? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑 所有聚合均移出 CTE
EDIT All aggregation moved out of the CTE
如下:
让我们假设这个模式:
该查询是自我解释的:
CTE 返回每个员工(#parent)的“叶子”列表,然后查询对该“叶子”的所有销售额求和。 您可以测试它的运行。
已编辑
查询已修复。
Here it is:
Let's supose this schema:
The query is self explained:
CTE returns a list of 'leafs' for each employee (#parent), then query sums all sales for this 'leafs'. You can test it running.
EDITED
Query is fixed.