我正在尝试编写一个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中有两行累加奖金。如何修改我的功能以获得正确的奖金?
答案 0 :(得分:5)
按员工分别对表进行分组,然后加入它们:
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
答案 1 :(得分:1)
您可以使用这样的子查询来执行此操作:
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
答案 2 :(得分:1)
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
;