私は、その四半期にボーナスを持っている従業員を含む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
IDと名前の両方が必要です – Pingpong
だから、それも選択してください。回答は修正されました。 – pete
ありがとうございます。しかし、それは2行を返します。 3行を返します。 – Pingpong