在sql中连接多行

时间:2013-03-15 11:05:56

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

我有一张这样的表

id    data
1     note1
1     note2
3     note6
3     note8

当我从该表中选择数据时,我希望将数据列值连接起来,如

select data 
from table 
where id = 1 --(this query is just for demonstration )

需要提供类似

的输出
note1+note2

有没有办法实现这个目标?

注意:我曾尝试使用COALESCE(我从Vishal获得)并且它也无效。这就是我的实际查询现在的样子

    declare @var1 varchar(200)

SELECT     dbo.kt_missingdataview.Varenummer, dbo.kt_missingdataview.Varenavn, dbo.kt_missingdataview.Producentvarenummer,
                          (SELECT     dbo.ETEXT.TXT1
                            WHERE      (dbo.ETEXT.ID = 1)) AS shortdesc,
                            (SELECT @var1 = COALESCE(@var1 + '+', '') +  dbo.ETEXT.TXT1 from dbo.ETEXT 
Select @var1),
                          (SELECT     dbo.ETEXT.TXT1
                            WHERE      (dbo.ETEXT.ID = 2)) AS longdesc, dbo.ETEXT.REFKEY, dbo.ETEXT.ID
FROM         dbo.kt_missingdataview INNER JOIN
                      dbo.ETEXT ON dbo.kt_missingdataview.Varenummer = dbo.ETEXT.REFKEY
WHERE     (dbo.ETEXT.ELANGUAGE = 0) 

4 个答案:

答案 0 :(得分:2)

对于SQL Server,您可以使用COALESCE

declare @var1 varchar(200)
SELECT @var1 = COALESCE(@var1 + '+', '') +  data from the_table where id = 1
Select @var1

输出:note1+note2

答案 1 :(得分:1)

你没有指定DBMS所以我假设P​​ostgres:

select id, string_agg(data, '+')
from the_table
group by id;

答案 2 :(得分:1)

在MySQL中,使用GROUP_CONCAT function

SELECT id, group_concat(data)
FROM TABLENAME 
WHERE ID=1

答案 3 :(得分:1)

在SQL Server中,您可以使用FOR XML PATH来获取结果:

select distinct t1.id,
  STUFF((SELECT distinct '+ ' + t2.data
         from yourtable t2
         where t1.id = t2.id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') data
from yourtable t1;