SELECT t1.organization_id, t1.organization_name, SUM( t2.jl_amount ) yfSjAmount, SUM( t2.sj_amount ) yfJlAmount, SUM( t3.money ) yfSectionAmount, SUM( t3.mileage ) yfSectionLength FROM main_project t1 LEFT JOIN mat_approval_project t2 ON t2.main_id = t1.id LEFT JOIN mat_project_pavement_approval t3 ON t3.project_id = t2.id WHERE t1.project_general_name = '预防性养护' AND t1.project_category_name = '路面工程' AND t1.process_status = '100' AND t1.organization_id = 'b3f029fa-62ab-476e-9876-b87ce69c41c5' AND t1.project_year = '2023'; 该sql中t2和t3是一对多关系导致t2统计数据有误,如何修改
时间: 2024-03-13 22:44:15 浏览: 38
可以使用子查询的方式来解决t2和t3之间是一对多关系的问题,将t2和t3的数据分别聚合后再进行连接。修改后的SQL语句如下:
```
SELECT t1.organization_id, t1.organization_name, SUM(t2.yfSjAmount) yfSjAmount, SUM(t2.yfJlAmount) yfJlAmount, SUM(t3.yfSectionAmount) yfSectionAmount, SUM(t3.yfSectionLength) yfSectionLength
FROM main_project t1
LEFT JOIN (
SELECT main_id, SUM(jl_amount) yfSjAmount, SUM(sj_amount) yfJlAmount
FROM mat_approval_project
GROUP BY main_id
) t2 ON t2.main_id = t1.id
LEFT JOIN (
SELECT project_id, SUM(money) yfSectionAmount, SUM(mileage) yfSectionLength
FROM mat_project_pavement_approval
GROUP BY project_id
) t3 ON t3.project_id = t2.id
WHERE t1.project_general_name = '预防性养护'
AND t1.project_category_name = '路面工程'
AND t1.process_status = '100'
AND t1.organization_id = 'b3f029fa-62ab-476e-9876-b87ce69c41c5'
AND t1.project_year = '2023'
GROUP BY t1.organization_id, t1.organization_name;
```
这里使用了两个子查询,分别对t2和t3中的数据进行了聚合,然后再与t1进行了连接。GROUP BY子句用于对结果进行分组,以便进行聚合操作。
阅读全文