为什么sql中的结果和原始数据的结果不兼容?

rslzwgfq  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(327)

我有两张table

table1
id,link_kd, scost, syear

table2
id,link_kd, hcost, hyear

这是我的小提琴
当我使用“求和联接”和“按年份分组”时,结果不兼容,但如果我进行单个查询,结果是准确的,有人能帮我吗?
我想把成本和成本按年度相加。如果有年份但没有数据scost或hcost,结果为零。但主要的问题是我的查询与结果不一致

e5nszbig

e5nszbig1#

假设你想得到一个单一的金额每年,这里有一个选择使用 union all :

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;

根据您的评论,如果您想要多个总和,您必须创建一个年份表,然后使用 outer joins 得到你的成本和成本。举个例子:

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

相关问题