我正在尝试汇总子公司的支出,包括所有没有任何递归函数的孙子公司。
我的数据集看起来类似于这种格式:
Parent A
- Child A.1 - $1,000
- Child A.2 - $2,000
- - Grandchild A.2.1 - $500
- - Grandchild A.2.2 - $750
- Child A.3 - $3,000
- Child A.4 - $4,000
Parent B
- Child B.1 - $11,000
- Child B.2 - $12,000
- - Grandchild B.2.1 - $1,500
- - Grandchild B.2.2 - $1,750
- Child B.3 - $13,000
- Child B.4 - $14,000
我想做的是按父 A 的 child 求和,所以结果输出如下:
Child A.1 - $1,000
Child A.2 - $3,250
Child A.3 - $3,000
Child A.4 - $4,000
这是我的公司表的简化结构:
id
name
parent_id
lft
rght
这是我的支出表的简化结构:
id
company_id
amount
date
我知道如何列出每个 child 及其 parent A 的金额:
SELECT
`Company`.`name` AS `name`,
SUM(`Spend`.`amount`) AS `amount`
FROM
`spend_table` AS `Spend`
INNER JOIN companies_table AS `Company` ON `Spend`.`company_id` = `Company`.`id`
INNER JOIN companies_table AS `thisCompany` ON `Company`.`lft` BETWEEN `thisCompany`.`lft` AND `thisCompany`.`rght`
WHERE
`thisCompany`.`name` = 'Parent A'
GROUP BY
`Company`.`name`
哪个会输出:
Child A.1 - $1,000
Child A.2 - $2,000
Grandchild A.2.1 - $500
Grandchild A.2.2 - $750
Child A.3 - $3,000
Child A.4 - $4,000
而且我知道如何为父 A 的每个 child (不包括孙子)求和:
SELECT
`Company`.`name` AS `name`,
SUM(`Spend`.`amount`) AS `amount`
FROM
`spend_visibility2` AS `SpendVisibility`
`spend_table` AS `Spend`
INNER JOIN companies_table AS `Company` ON `Spend`.`company_id` = `Company`.`id`
INNER JOIN companies_table AS `thisCompany` ON `Company`.`lft` BETWEEN `thisCompany`.`lft` AND `thisCompany`.`rght`
WHERE
`thisCompany`.`name` = 'Parent A'
`Company`.`parent_id` = `thisCompany`.`id`
GROUP BY
`Company`.`name`
哪个会输出:
Child A.1 - $1,000
Child A.2 - $2,000
Child A.3 - $3,000
Child A.4 - $4,000
有人可以帮助我吗?我相信我需要一个子选择,但我很难弄明白。
最佳答案
首先,选择您感兴趣的子公司(表 c)。我使用子查询轻松选择“父 A”上的直接子级。然后再次加入 companies_table 以检索所有后代(表别名 c2)。最后加入您的 spend_table 以获取您可以使用 group by 汇总的金额。
select c.name, sum(s.amount)
from companies_table c
join companies_table c2 ON c2.lft between c.lft and c.rght
join spend_table s ON c2.id = s.company_id
where parent_id = (select id from companies_table where name = 'Parent A')
group by c.name
关于mysql - 改进的预序树遍历子卷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6903015/