I have two tables (one for quarter one, one for quarter two), each of which contains employees who have bonus in that quarter. Every employee has a unique id in the company.
I want to get all employees who has bonus in either q1 or q2. No duplicate employee is needed. Both Id, and Amount are required.
Below is my solution, I want to find out if there is a better solution.
declare @q1 table (
EmployeeID int identity(1,1) primary key not null,
amount int
)
declare @q2 table (
EmployeeID int identity(1,1) primary key not null,
amount int
)
insert into @q1
(amount)
select 1
insert into @q1
(amount)
select 2
select * from @q1
insert into @q2
(amount)
select 1
insert into @q2
(amount)
select 11
insert into @q2
(amount)
select 22
select * from @q2
My Solution:
;with both as
(
select EmployeeID
from @q1
union
select EmployeeID
from @q2
)
select a.EmployeeID, a.amount
from @q1 as a
where a.EmployeeID in (select EmployeeID from both)
union all
select b.EmployeeID, b.amount
from @q2 as b
where b.EmployeeID in (select EmployeeID from both) and b.EmployeeID NOT in (select EmployeeID from @q1)
Result:
EmployeeID, Amount
1 1
2 2
3 22
The subselect UNIONS both tables together. The GROUP BY gives you one row per employee and the SUM means that if someone got lucky in both qs then you get the total. I’m guessing that’s the right thing for you.