我有一张表group
CREATE TABLE
GROUP (id , HOST , participant)
INSERT INTO GROUP(id, HOST, participant)
VALUES (1, 1000, 2000)
INSERT INTO GROUP (id, HOST, participant)
VALUES (1, 1000, 2000)
customer
表
insert into customer( custmerid, customername, alias) values (1000,'abccorp', 'abc')
insert into customer( custmerid, customername, alias) values (2000,'bcacorp', 'bca')
insert into customer( custmerid, customername, alias) values (3000,'lcacorp', 'lca')
现在我想写一个视图来获取
groupID, host participation
1 abccorp bcacorp
2 abccorp null
3 null lcacorp
我怎么能得到这个?我看到组织需要两个连接。但我怎么能得到它?
感谢。
答案 0 :(得分:0)
如果我没有误解你的问题,以下陈述将返回你需要的结果。
Host
已映射到custmerid
Participant
已映射到custmerid
请注意,如果custmerid
不是您问题中的拼写错误,我建议您完全拼写为customerid
SELECT groupid = g.id
, host = chost.customername
, participation = cparticipant.customername
FROM [Group] g
LEFT OUTER JOIN Customer chost ON chost.custmerid = g.Host
LEFT OUTER JOIN Customer cparticipant ON cparticipant.custmerid = g.Participant
;WITH [Group](ID, Host, Participant) AS (
SELECT 1, 1000, 2000
UNION ALL SELECT 2, 1000, NULL
UNION ALL SELECT 3, NULL, 3000
)
, Customer (custmerid, customername, alias) AS (
SELECT 1000, 'abccorp', 'abc'
UNION ALL SELECT 2000, 'bcacorp', 'bca'
UNION ALL SELECT 3000, 'lcacorp', 'lca'
)
SELECT groupid = g.id
, host = chost.customername
, participation = cparticipant.customername
FROM [Group] g
LEFT OUTER JOIN Customer chost ON chost.custmerid = g.Host
LEFT OUTER JOIN Customer cparticipant ON cparticipant.custmerid = g.Participant
groupid host participation
----------- ------- -------------
1 abccorp bcacorp
2 abccorp NULL
3 NULL lcacorp