加入给出不正确的总和

Join gives incorrect sum

我正在尝试编写一个 select 语句,为每个名称收集一行。因此,预期输出为:

姓名=Al,薪水=30,奖金=10

Table_1

Name   Salary
Al     10
Al     20

Table_2

Name  Bonus
Al    5
Al    5

我该怎么写? 我尝试:

Select t1.Name, SUM(t1.Salary), SUM(t2.Bonus) FROM table_1 t1
LEFT JOIN table_2 t2 
ON t1.Name=t2.Name
Group By 1

我得到奖金 20 而不是 10 作为奖金。这可能是因为 t1 中有两行是从中总结奖金的。我怎样才能修改我的功能以获得正确的奖金?

按员工分别对表进行分组,然后加入它们:

SELECT t1.Name, Salary, Bonus
FROM (
  SELECT Name, SUM(Salary) Salary
  FROM table_1
  GROUP BY Name
) t1
LEFT JOIN (
  SELECT Name, SUM(Bonus) Bonus
  FROM table_2
  GROUP BY Name
) t2 ON t1.Name = t2.Name

你可以用这样的子查询来完成:

declare @salary table (Name varchar(100), value int)
declare @bonus table (Name varchar(100), value int)

insert into @salary
values ('al', 10)

insert into @salary
values ('al', 20)

insert into @bonus
values ('al', 5)

insert into @bonus
values ('al', 5)


select s.Name, sum(value) as Salary, Bonus
from @salary s JOIN 
(
    select Name, sum(value) as Bonus
    from @bonus 
    group by Name 
) b on b.name = s.Name
group by s.Name, b.Bonus
SELECT 
  coalesce(t1.name,t2.name) name, 
  coalesce(sum(t1.salary),0) salary_total, 
  coalesce(sum(t2.bonus),0) bonus_total
FROM 
  (select name, sum(salary) salary from salary_table group by 1) t1
FULL OUTER JOIN 
  (select name, sum(bonus) bonus from bonus_table group by 1) t2
ON (t1.name=t2.name)
GROUP BY 1
;