【发布时间】:2011-08-11 03:45:29
【问题描述】:
这是代码,显示了输入和所需的输出。
基本上,我正在尝试自我加入,以将我的经纪人声明的结果与我的内部记录相匹配。所以左边的一组列是经纪人的名单,右边是我的名单。如果经纪人有头寸,而我没有,右边的空值。如果我有头寸而经纪人没有头寸,则左侧为 NULL。
left join + right join + union 完全符合我的要求。似乎应该有一些巫术来允许完全加入而无需两次选择即可获得它,但我无法弄清楚。
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
【问题讨论】:
-
你用的是什么版本的sql?