I have two tables :
One for employees data
Employee
Another for employee vacations balance
VacBal
Now i want to get the current vacation balance for each employee,considering if the emp_num = 0
then it's a general balance
for all employees not for specific employee
If Employee table Sample data like that :
emp_num name
546 john
134 Ramy
and
VacBal like that
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
I want result set like this :
emp_num name SUM(bal_num)
546 john 10 --->3+7
134 Ramy 8 --->1+7
How to do this ?
You can use a correlated sub-query to 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.