将单个列连接成一行

时间:2014-04-28 14:16:47

标签: sql-server-2012

我有一个查询

select 
     [I].[name_Text] as [Name] 
        from 
      [dbo].[payments$] [G]
    inner join
        [dbo].[payment$] [H]
    on 
        [H].payments_Id = [G].payments_Id
    inner join
        [dbo].[Payment] [I]
    on 
        [I].[payment_Id] = [H].payment_Id
    WHERE 
        [G].restaurant_Id = 0 and [I].[lang] = 'en'

我的输出为

Name
-----------------
American Express
EuroCard / MasterCard
VISA
VISA Electron

我需要像American Express,EuroCard / MasterCard,VISA,VISA Electron这样的输出

我尝试这个查询

DECLARE @Names VARCHAR(Max)  
SELECT @Names = COALESCE([A].[Name] + ' ','') 
        FROM  
            (select [I].[name_Text] as [Name] from [dbo].[payments$] [G]
        inner join
            [dbo].[payment$] [H]
        on 
            [H].payments_Id = [G].payments_Id
        inner join
            [dbo].[Payment] [I]
        on 
            [I].[payment_Id] = [H].payment_Id
        WHERE 
            [G].restaurant_Id = 0 and [I].[lang] = 'en') A
SELECT @Names as [name]

但我退出了

name
----------
VISA Electron 

任何其他方式

1 个答案:

答案 0 :(得分:1)

这种群组连接方式实际上是不受支持的,其行为可能是不确定的。无论如何,你需要使用:

DECLARE @Names VARCHAR(Max) = ''
SELECT @Names = @Names + COALESCE([A].[Name] + ' ','') 
        FROM  
            (select [I].[name_Text] as [Name] from [dbo].[payments$] [G]
        inner join
            [dbo].[payment$] [H]
        on 
            [H].payments_Id = [G].payments_Id
        inner join
            [dbo].[Payment] [I]
        on 
            [I].[payment_Id] = [H].payment_Id
        WHERE 
            [G].restaurant_Id = 0 and [I].[lang] = 'en') A
SELECT @Names as [name]