-2

我有一张这样的桌子

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

4 回答 4

2

对于 SQL Server,您可以使用COALESCE

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

输出:note1+note2

于 2013-03-15T11:13:21.703 回答
1

您没有指定 DBMS,所以我假设 Postgres:

select id, string_agg(data, '+')
from the_table
group by id;
于 2013-03-15T11:09:50.783 回答
1

在 MySQL 中,使用GROUP_CONCAT 函数

SELECT id, group_concat(data)
FROM TABLENAME 
WHERE ID=1
于 2013-03-15T11:14:07.957 回答
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;
于 2013-03-15T11:21:54.700 回答