我有两张桌子:
一个用于员工数据
Employee
另一个员工休假余额
VacBal
现在我想获得每位员工的当前假期余额,考虑emp_num = 0
是否所有员工都是general balance
而不是特定员工
如果Employee表样本数据如下:
emp_num name
546 john
134 Ramy
和
像这样的VacBal
emp_num bal_num bal_date
546 1 5-5-2015
546 2 6-5-2015
134 1 7-5-2015
0 3 2-2-2015
0 4 6-1-2015
我想要这样的结果集:
emp_num name SUM(bal_num)
546 john 10 --->3+7
134 Ramy 8 --->1+7
怎么做?
答案 0 :(得分:3)
您可以使用相关的子查询SUM
:
select e.emp_num, e.name, (select sum(vb.bal_num) from VacBal vb
where vb.emp_num in (e.emp_num,0))
from Employee e
答案 1 :(得分:3)
SELECT e.emp_num,
name,
Sum(bal_num) + (SELECT Sum(bal_num)
FROM vacbal vb
WHERE emp_num = 0)
FROM employee e
inner join vacbal v on e.emp_num=v.emp_num
GROUP BY e.emp_num,
name