我有桌子。如何在工资中添加奖金?
在一般情况下,
Workers
和Bonuses
查询sum
提高奖金或采取最大的 -max
一个。null
- 如果工人没有任何奖金像这样的东西
select w.WorkerId,
w.WorkerName,
w.CompanyId,
w.Salary + coalesce((select sum(b.Bonus) -- Let's sum up all worker's the bonuses
from Bonuses b
where b.WorkerId = w.WorkerId), 0)
from Workers w
如果你想要update
现有的Workers
表,同样的原则:
update Workers
set Salary = Salary + coalesce((select sum(b.Bonus)
from Bonuses b
where b.WorkerId = WorkerId), 0);
但是,正如我所见,您在and之间具有一对一的关系,这就是为什么会这样做(请参阅Wanderer 的解决方案)。更好的方法是结合和表格:Workers
Bonuses
left join
Workers
Bonuses
Worker:
WorkerId
WorkerName,
CompanyId,
Salary not null,
Bonus not null default 0 -- <- from Bonuses
因此,您可以将查询简单化为
select ...
Salary + Bonus
from Workers
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句