通过另一个表的字段连接表组的列字段

时间:2016-01-04 13:17:33

标签: sql sql-server concatenation

我有两个表说t1和t2与testid连接。如果表t1的d1,d2和id相同,我需要连接t2的val列。请参考下表。

    CREATE TABLE #t1 (d1 varchar(100),d2 varchar(100),id int,testid int)

    INSERT INTO #t1 (d1,d2,id,testid) VALUES ('p','q',1,101)
    INSERT INTO #t1 (d1,d2,id,testid) VALUES ('r','s',2,102)
    INSERT INTO #t1 (d1,d2,id,testid) VALUES ('p','q',1,103)
    INSERT INTO #t1 (d1,d2,id,testid) VALUES ('r','s',1,104)

    CREATE TABLE #t2 (testid int,val varchar(100))

    INSERT INTO #t2 (testid,val) values (101,'x')
    INSERT INTO #t2 (testid,val) values (102,'y')
    INSERT INTO #t2 (testid,val) values (103,'z')
    INSERT INTO #t2 (testid,val) values (104,'xx')

The result should be:

    d1 d2 pid val
    p  q  1   x,z
    r  s  2   y
    r  s  1   xx

1 个答案:

答案 0 :(得分:1)

IF OBJECT_ID('tempdb.dbo.#t1') IS NOT NULL
    DROP TABLE #t1

IF OBJECT_ID('tempdb.dbo.#t2') IS NOT NULL
    DROP TABLE #t2

CREATE TABLE #t1 (d1 VARCHAR(100), d2 VARCHAR(100), id INT, testid INT)
INSERT INTO #t1 (d1, d2, id, testid)
VALUES ('p', 'q', 1, 101)
     , ('r', 's', 2, 102)
     , ('p', 'q', 1, 103)
     , ('r', 's', 1, 104)

CREATE TABLE #t2 (testid INT, val VARCHAR(100))
INSERT INTO #t2 (testid, val)
VALUES (101, 'x')
     , (102, 'y')
     , (101, 'z')
     , (104, 'xx')

SELECT *
FROM (
    SELECT d1, d2, id, value = STUFF((
        SELECT [text()] = ',' + val
        FROM #t2
        WHERE #t2.testid = #t1.testid
        FOR XML PATH('')), 1, 1, '')      
    FROM #t1
) t
WHERE t.value IS NOT NULL

输出 -

d1  d2  id   value
--- --- ---- ----------------
p   q   1    x,z
r   s   2    y
r   s   1    xx