在sql中只连接一列

时间:2018-03-12 08:16:44

标签: sql sql-server

booking No  Movie Name      Guest Name
---------------------------------------------
643042      Horrer Movie    MARLON HARRIS
643042      Horrer Movie    ALICE HARRIS

我想在SQL Server

中显示如下记录
643042  Horrer Movie    ALICE HARRIS / MARLON HARRIS

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

ArrayList

答案 1 :(得分:0)

如评论中所述,使用FOR XML PATH

    ;WITH T ([booking No] , [Movie Name] ,     [GuestName])
    AS
    (
    SELECT 643042   ,   'Horrer Movie',    'MARLON HARRIS'
    UNION ALL 
    SELECT 643042   ,   'Horrer Movie',    'ALICE HARRIS'
    )

    SELECT [booking No] , [Movie Name] ,
        GuestNames = LTRIM(RTRIM(STUFF(CAST((SELECT ' / '+ B.[GuestName]
        FROM T B
        WHERE a.[booking No] = b.[booking No]
        FOR XML PATH (''),TYPE) AS NVARCHAR(1000)),1,2,''))) 
    FROM T A
    GROUP BY [booking No] , [Movie Name]