我有多个表遵循从其成本计算阶段到开票阶段的报销请求,在请求的每个阶段记录订单项及其值。
为了获得每个阶段的每个费用类别的总数,我使用选择对它们进行求和 - 我无法弄清楚的是一种有效的方法来总结整个阶段的总计,而无需另外求和请求。由于这会查询数十万行 - 响应时间正在受到影响。当前的方法需要不到4.59秒 - 而当我删除总计的总和需要4.02秒时 - 任何关于如何使用原始总和来获得总计的建议都是非常受欢迎的:
SELECT p.program_name, p.id as program_id, p.entity_id, a.id as account_id,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 9 and c.account_id = a.id) as NIPLoanCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 2 and c.account_id = a.id) as AcquisitionCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 3 and c.account_id = a.id) as PreDemoCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 4 and c.account_id = a.id) as DemolitionCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 5 and c.account_id = a.id) as GreeningCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 6 and c.account_id = a.id) as MaintenanceCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 7 and c.account_id = a.id) as AdministrationCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 8 and c.account_id = a.id) as OtherCost,
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE c.account_id = a.id)
as TotalCost,
/* I have removed the other 4 table's requests that follow this same methodology */
FROM programs p, accounts a WHERE p.entity_id = a.entity_id;
答案 0 :(得分:4)
您可以使用带有SELECT p.program_name,
p.id as program_id,
p.entity_id,
t.*
FROM programs p
INNER JOIN accounts a
ON p.entity_id = a.entity_id
INNER JOIN
(
SELECT a.id AS account_id,
SUM(CASE WHEN c.expense_category_id = 9 THEN c.amount ELSE 0 END) AS NIPLoanCost,
SUM(CASE WHEN c.expense_category_id = 2 THEN c.amount ELSE 0 END) AS AcquisitionCost,
SUM(CASE WHEN c.expense_category_id = 3 THEN c.amount ELSE 0 END) AS PreDemoCost,
SUM(CASE WHEN c.expense_category_id = 4 THEN c.amount ELSE 0 END) AS DemolitionCost,
SUM(CASE WHEN c.expense_category_id = 5 THEN c.amount ELSE 0 END) AS GreeningCost,
SUM(CASE WHEN c.expense_category_id = 6 THEN c.amount ELSE 0 END) AS MaintenanceCost,
SUM(CASE WHEN c.expense_category_id = 7 THEN c.amount ELSE 0 END) AS AdministrationCost,
SUM(CASE WHEN c.expense_category_id = 8 THEN c.amount ELSE 0 END) AS OtherCost,
COALESECE(SUM(c.amount), 0) AS TotalCost
FROM accounts a
LEFT JOIN cost_items c
ON a.id = c.account_id
GROUP BY a.id
) t
ON a.id = t.account_id
表连接的条件聚合来替换所有子查询。这样的事情应该有效:
(SELECT COALESCE(SUM(amount),0) FROM cost_items c WHERE expense_category_id = 9 and c.account_id = a.id)
请注意,原始方法的缺陷是相关的子查询,如下所示:
programs
对于accounts
和cost_items
表的连接产品中的每条记录,您发出了一个单独的查询(实际上是其中许多),它正在扫描整个accounts
表以确定和。在我的方法中,我们只通过cost_items
和{{1}}的联接,这就是节省时间的地方。