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

时间:2018-12-06 19:24:25

标签: mysql mysqli

我有两个桌子

table1
id,link_kd, scost, syear

table2
id,link_kd, hcost, hyear

this my fiddle

当我使用连接求和和按年分组时,结果不兼容 但是如果我进行单个查询,结果是准确的 有人可以帮我吗?

我想按年对成本和成本进行总和。如果有年份但没有数据成本或成本,则结果为零。 但是主要问题是我的查询与结果不兼容

1 个答案:

答案 0 :(得分:1)

假设您希望每年获得一笔款项,这是使用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来获取scost和hcost。这是一个示例:

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