T-SQL最后并排耦合数据

时间:2018-02-27 12:18:04

标签: sql-server tsql

在下面的屏幕截图中,我想将YorumYapanAdsoyad列中的数据合并到一行中。

enter image description here

enter image description here

应该是这样的;

 8 | Fiat Linea 1.3 Multijet | Ahmet, Selami
12 | Vw Golf                 | Ertem, Selim

感谢您的帮助;)

3 个答案:

答案 0 :(得分:2)

对于SQL(2016及以下版本)的早期版本

,请尝试此操作
       ;WITH Tmp (UrunId, Araclar , YorumYapanSoyad) as
       (
       SELECT 8 , 'Fiat Line 1.3 Multijet' , 'Ahmet'
       UNION ALL 
       SELECT 8 , 'Fiat Line 1.3 Multijet' , 'Selami'
       UNION ALL 
       SELECT 12 , 'Vw Golf' , 'Ertem'
       UNION ALL 
       SELECT 12 , 'Vw Golf' , 'Selim'

       )


       SELECT UrunId ,  Araclar ,
        (SELECT STUFF(
                (SELECT ', ' + YorumYapanSoyad 
                FROM Tmp b
                WHERE B.Araclar = T.Araclar
                AND b.UrunId = t.UrunId 
                FOR XML PATH (''),TYPE).value('.','nvarchar(max)'),1,2,'') 
        ) YorumYapanSoyad

       FROM Tmp t
       GROUP BY UrunId ,  Araclar

答案 1 :(得分:1)

试试这个

DECLARE @Table TABLE (ID INT,Araclar varchar(100),YorumYapan varchar(20))
INSERT INTO @Table
SELECT 8 , 'Fiat Linea 1.3 Multijet' , 'Ahmet'  UNION ALL
SELECT 8 , 'Fiat Linea 1.3 Multijet' , 'Selami' UNION ALL
SELECT 12 , 'Vw Golf'                 , 'Ertem' UNION ALL
SELECT 12 , 'Vw Golf'                 , 'Selim'

SELECT DISTINCT  ID
                ,Araclar
                ,STUFF((SELECT ', '+YorumYapan 
                    FROM @Table i WHERE i.ID=o.ID FOR XML PATH ('')),1,1,'') AS YorumYapan
FROM @Table o

结果

ID  Araclar                  YorumYapan
------------------------------------------
8   Fiat Linea 1.3 Multijet  Ahmet, Selami
12  Vw Golf                  Ertem, Selim

答案 2 :(得分:0)

这是我使用的配方。由于我不知道你的表名,我使用sys.tables和sys.columns来做这个例子。基本上,函数STUFF是你的朋友。

SELECT
    t.name,
    STUFF 
        (
            (
                SELECT ', ' + c.name
                FROM sys.columns c
                WHERE c.object_id = t.object_id
                FOR XML PATH('')
            ), 
            1, /*string start*/
            2, /*string length*/
            '' /*replaceWith*/
        )
FROM sys.tables t