我正在努力扩大儿童公司的支出,包括所有孙子公司,而没有任何递归功能。
我的数据集看起来与此格式类似:
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 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
我知道如何列出每个孩子及其父母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的每个孩子(不包括孙子女)求和:
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
有人能帮助我吗?我相信我需要一个子选择,但我很难搞清楚。
答案 0 :(得分:0)
首先,选择您感兴趣的子公司(表c)。我使用了一个子查询来轻松选择'Parent 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