显示两个表中的唯一行

时间:2012-02-15 02:44:49

标签: tsql

我有两张桌子(一张用于第一季度,一张用于第二季度),每张桌子都包含在该季度有奖金的员工。每个员工在公司都有一个独特的身份。

我想让所有在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

3 个答案:

答案 0 :(得分: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

子选择UNIONS两个表一起。 GROUP BY为每位员工提供一行,而SUM意味着如果有人在两个q中都运气好,那么你就得到总数。我猜这对你来说是对的。

答案 1 :(得分: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

答案 2 :(得分: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