2

我正在尝试汇总子公司的支出,包括所有没有任何递归函数的孙子公司。

我的数据集看起来类似于这种格式:

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

有人能帮我吗?我相信我需要一个子选择,但很难弄清楚。

4

1 回答 1

0

首先,选择您感兴趣的子公司(表 c)。我使用子查询轻松选择“父 A”上的直接子级。然后再次加入 Companies_table 以检索所有后代(表别名 c2)。最后加入您的支出表以获取您可以使用 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
于 2011-08-01T21:19:39.837 回答