我有两张表格(第一季度一个,第二季度一个),每个表格包含在该季度有奖金的员工。每个员工在公司都有一个唯一的ID。显示来自两个表格的唯一行
我想让所有员工在q1或q2中获得奖金。 没有重复雇员是必要的。需要ID和金额。
以下是我的解决方案,我想知道是否有更好的解决方案。
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
我的解决方案:
;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
身份证和姓名都是必填项 – Pingpong 2012-02-15 02:57:39
所以选择它也是如此。答复修改。 – pete 2012-02-15 02:59:54
谢谢。但它返回2行。它应该返回3行。 – Pingpong 2012-02-15 03:11:17