SELECT year, SUM(scost) scostsum,
FROM (
SELECT syear as year, scost as cost from table1
UNION ALL
SELECT hyear as year, hcost as cost from table2
) t
GROUP by year;
select year, coalesce(s.cost,0) as scost, coalesce(h.cost,0) as hcost
from (select syear as year from table1 union select hyear from table2) years
left join (
select syear, sum(scost) cost
from table1
group by syear) s on years.year = s.syear
left join (
select hyear, sum(hcost) cost
from table2
group by hyear) h on years.year = h.hyear
1条答案
按热度按时间e5nszbig1#
假设你想得到一个单一的金额每年,这里有一个选择使用
union all
:根据您的评论,如果您想要多个总和,您必须创建一个年份表,然后使用
outer joins
得到你的成本和成本。举个例子: