[英]Concatenate the columns from two result sets
我有一個桌子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
我怎么能得到這個? 我看到該組織需要兩個加入。 但是我怎么能得到它呢?
謝謝。
如果我沒有誤解您的問題,以下聲明將返回您所需的結果。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.