合并多行

时间:2018-11-14 09:38:51

标签: sql sql-server

我有这个东西,我不知道该怎么解决。

表1:项目

ID | NO_ 
1 | SX1234
2 | SXABCD

表2:文字

Reffilename | RefKey | LanguageCode | ID | LineNumber | Txt1
Product | SX1234 | ENU | 2 | 0 | This is
Product | SX1234 | ENU | 2 | 1 | my text
Product | SX1234 | ENU | 2 | 2 | I want to come 
Product | SX1234 | ENU | 2 | 3 | out in one field
....

我可以做到

SELECT i.[No]_, t.[Txt1] 
FROM ITEMS AS i
INNER JOIN 
TEXT AS t ON i.[no_] = t.RefKey
WHERE t.Reffilename = 'Prouduct' AND t.LanguageCode = 'ENU' AND t.ID = 2 AND i.[No_] = 'SX1234'

那给了我这个结果。

SXI1234 | This is
SXI1234 | my text
SXI1234 | I want to come
SXI1234 | out in one field

但是我想合并文本,所以我的输出将是:

SXI1234 | This is my text I Want to come out in one field

我该如何解决?

3 个答案:

答案 0 :(得分:0)

SELECT a.RefKey,Stuff((SELECT ''+ Txt1  FROM Text
where a.Id=b.Id
 FOR
 XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N''
) As Text 
from ITEMS a
group by a.Id

答案 1 :(得分:0)

尝试使用STUFF()函数

SELECT i.[No]_, text= STUFF((
    SELECT ', ' + t.[Txt1] 
    FROM ITEMS AS a
    INNER JOIN 
    TEXT AS t ON i.[no_] = t.RefKey
    WHERE a.[No]_= i.[No]_
    FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '')
FROM ITEMS AS i
GROUP BY i.[No]_

答案 2 :(得分:0)

DECLARE @t1 TABLE (Id INT, Num CHAR (7))
INSERT INTO @t1
    VALUES (1, 'SX1234'), (2, 'SXABCD')
DECLARE @t2 TABLE (Reffilename Char(8), RefKey CHAR (7), LanguageCode  CHAR(4), ID INT, LineNumber INT, Txt1 VARCHAR(MAX))
INSERT INTO @t2
    VALUES ('Product', 'SX1234', 'ENU', 2, 0, 'This isa,
    ('Product', 'SX1234', 'ENU', 2, 1, 'my text'),
    ('Product', 'SX1234', 'ENU', 2, 2, 'I want to come'),
    ('Product', 'SX1234', 'ENU', 2, 3, 'out in one field')

SELECT DISTINCT RefKey, Result = STUFF((SELECT ' ' + t2.Txt1
                                FROM @t1 t1
                                JOIN @t2 t2 ON t1.Num = t2.RefKey 
                                FOR XML PATH('')), 1, 1, '' ) 
FROM @t2