2012-02-15 61 views
0

我有两张表格(第一季度一个,第二季度一个),每个表格包含在该季度有奖金的员工。每个员工在公司都有一个唯一的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 

回答

1
SELECT EmployeeID, Name, SUM(amount) AS TotalBonus 
FROM 
(SELECT EmployeeID, Name, amount 
from @q1 
UNION ALL 
SELECT EmployeeID, Name, amount 
from @q2) AS all 
GROUP BY EmployeeID, Name 

子选择UNION两个表在一起。 GROUP BY为每个员工提供一行,SUM意味着如果某人在两个qs都有幸运,那么您可以获得总数。我猜这对你来说是正确的。

0

尝试:

SELECT DISTINCT q1.EmployeeID --- Same as q2.EmployeeID thanks to the join 
     , q1.EmployeeName -- Not defined in OP source. 
FROM @q1 AS q1 
     CROSS JOIN @q2 AS q2 
WHERE q1.amount IS NOT NULL 
     OR q2.amount IS NOT NULL 
+0

身份证和姓名都是必填项 – Pingpong 2012-02-15 02:57:39

+0

所以选择它也是如此。答复修改。 – pete 2012-02-15 02:59:54

+0

谢谢。但它返回2行。它应该返回3行。 – Pingpong 2012-02-15 03:11:17

0

试试这个:

SELECT EmployeeID 
FROM EmployeeList 
WHERE EmployeeID IN 
    (SELECT EmployeeID From QuarterOne 
     UNION 
    SELECT EmployeeID From QuarterTwo) 

或使用JOIN

SELECT EmployeeID 
FROM EmployeeList a INNER JOIN QuarterTwo b 
      ON a.EmployeeID = b.EmployeeID 
    INNER JOIN QuarterTwo c 
      ON a.EmployeeID = c.EmployeeID 

这将返回在任一季度都有记录的所有EmployeeID

+0

什么是EmployeeList? – Pingpong 2012-02-15 02:56:25

+0

@Pingpong'EmployeeList'是表的名称。您可以将其更改为包含所有员工的表格名称。 – 2012-02-15 02:57:36

+0

问题 – Pingpong 2012-02-15 02:58:19