这是代码,显示输入和所需的输出。
基本上,我正在尝试 self 加入,以将经纪人声明的结果与我的内部记录进行匹配。所以左边的列是经纪人的列表,右边是我的列表。如果经纪人有仓位,而我没有,则右侧为 NULL。如果我有仓位而经纪商没有,则左侧为 NULL。
左连接+右连接+联合的工作方式完全符合我的要求。似乎应该有一些巫术来允许完全连接而无需两次选择,但我无法弄清楚。
drop table MatchPositions
go
create table MatchPositions
(
mt_source varchar (10),
mt_symbol varchar (10),
mt_qty float,
mt_price float
)
go
insert into MatchPositions values ('BROKER', 'IBM', 100, 50.25)
insert into MatchPositions values ('BROKER', 'MSFT', 75, 30)
insert into MatchPositions values ('BROKER', 'GOOG', 25, 500)
insert into MatchPositions values ('BROKER', 'SPY', 200, 113)
insert into MatchPositions values ('MODEL', 'MSFT', 75, 30)
insert into MatchPositions values ('MODEL', 'GOOG', 25, 500)
insert into MatchPositions values ('MODEL', 'GLD', 300, 150)
go
select * from MatchPositions b
left join MatchPositions m on b.mt_symbol = m.mt_symbol and m.mt_source = 'MODEL'
where b.mt_source = 'BROKER'
union
select * from MatchPositions b
right join MatchPositions m on b.mt_symbol = m.mt_symbol and b.mt_source = 'BROKER'
where m.mt_source = 'MODEL'
这是预期的输出:
mt_source mt_symbol mt_qty mt_price mt_source mt_symbol mt_qty mt_price
---------- ---------- ---------------------- ---------------------- ---------- ---------- ---------------------- ----------------------
NULL NULL NULL NULL MODEL GLD 300 150
BROKER GOOG 25 500 MODEL GOOG 25 500
BROKER IBM 100 50.25 NULL NULL NULL NULL
BROKER MSFT 75 30 MODEL MSFT 75 30
BROKER SPY 200 113 NULL NULL NULL NULL
最佳答案
;WITH T1 AS
(
SELECT *
FROM MatchPositions
WHERE mt_source = 'BROKER'
), T2 AS
(
SELECT *
FROM MatchPositions
WHERE mt_source = 'MODEL'
)
SELECT *
FROM T1 FULL JOIN T2 ON T1.mt_symbol = T2.mt_symbol
关于sql - 如何将此查询编写为完整联接而不是联合左/右联接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5758808/