连接两个结果集中的列

时间:2011-06-24 03:12:04

标签: sql sql-server sql-server-2008

我有一张表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

我怎么能得到这个?我看到组织需要两个连接。但我怎么能得到它?

感谢。

1 个答案:

答案 0 :(得分:0)

如果我没有误解你的问题,以下陈述将返回你需要的结果。

我正在使用以下假设

  • Host已映射到custmerid
  • Participant已映射到custmerid
  • 您提供的输入数据不完整

请注意,如果custmerid不是您问题中的拼写错误,我建议您完全拼写为customerid

SQL语句

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