我是SQL的新手,所以尝试了很多之后,我找不到合适的解决方案 在Stackoverflow上。这就是为什么我发表我的问题。[可能是重复的 问题]
我有2个表T1和T2。 给出的结构如下:
Tables:
T1:
Task Category Estimated_Cost
1 9100 100
2 9100 15
3 9100 6
4 9200 8
5 9200 11
T2:
Voucher Task Actual_Cost
1 1 10
2 1 20
3 1 15
4 2 32
5 4 8
6 5 3
7 5 4
我希望结果为:
Category Estimated_Cost Actual_Cost
9100 121 77
9200 19 15
对此使用哪个查询?
答案 0 :(得分:1)
嗯。 。 。这是一种方法:
select category, sum(estimated_cost) as estimated_cost, sum(actual_cost) as actual_cost
from ((select t1.category, t1.estimated_cost, 0 as actual_cost
from t1
) union all
(select t1.category, 0, t2.actual_cost
from t2 join
t1
on t1.task = t2.task
)
) cc
group by category;
答案 1 :(得分:1)
select *
from
(select t1.category, sum(t1.estimated_cost) estimated_cost
from t1
group by t1.category
) A
join
(select t1.category, sum(t2.actual_cost) actual_cost
from t2
join t1 on t1.task = t2.task
group by t1.category
) B
on A.category = B.category