2012-02-15 9 views
0

私は、その四半期にボーナスを持っている従業員を含む2つのテーブル(四半期ごとに1つ、四半期に2つ)を持っています。すべての従業員は会社内でユニークなIDを持っています。2つのテーブルから一意の行を表示

私は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 

副選択UNIONSの両方の表が一緒です。 GROUP BYは1人の従業員あたり1行を与え、SUMは誰かが両方のqで幸運になったら合計を得ることを意味します。私はそれがあなたにとって正しいことを推測しています。

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

IDと名前の両方が必要です – Pingpong

+0

だから、それも選択してください。回答は修正されました。 – pete

+0

ありがとうございます。しかし、それは2行を返します。 3行を返します。 – Pingpong

0

は、このいずれかを試してみてください。

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

OR 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

+0

@Pingpong 'EmployeeList'はテーブルの名前です。それを全従業員を含むテーブルの名前に変更することができます。 –

+0

質問にこのようなテーブルはありません – Pingpong

関連する問題