如果同一ID

时间:2018-02-24 19:02:08

标签: sql-server database tsql ssms

对于第一个1265的ID,我只想要一个这样的记录(见下图),现在我有三个不同的记录用于相同的ID并且不好。你可以看到在ID = 1265的第一个记录中,我希望将字符串连接成一个用','分隔的字符串:

1265 MARK, LISA, MAY

这是我的代码示例:

select 
    vup.UgovorId as ID, 
    concat(p.Naziv, p.Naziv) as NUMBER 
from 
    [TEST_Ugovori_Prod].dbo.VezaUgovorPartner as vup 
inner join 
    [TEST_MaticniPodaci2].[dbo].[Partner] as p on vup.PartnerId = p.PartnerID 
group by 
    vup.UgovorId, p.Naziv
order by 
    vup.UgovorId desc

以下是我的结果:

1265    MARK  
1265    LISA
1265    MAY
1264    LINDA  
1263    MARTINA
1262    MARKO                                                                                                                                                                                
1261    VIDAKS
1260    PEEKS 
1259    MARCUS
1258    MARKO                                                                                                                                                                                
1257    MATIA                                                                                                                                                                                 
1256    POPOVIC

1 个答案:

答案 0 :(得分:2)

SELECT ID, NUMBER = 
    STUFF((SELECT DISTINCT ', ' + NUMBER
           FROM example t2 
           WHERE t2.ID = t1.ID
          FOR XML PATH('')), 1, 2, '')
FROM example t1
GROUP BY ID
ORDER BY ID DESC

enter image description here

[DEMO HERE]

如果您在使用上述查询时遇到问题,这应该会有所帮助:

SELECT vup.UgovorId as ID, 
     STUFF((SELECT DISTINCT ', ' + p2.Naziv  
           FROM [TEST_Ugovori_Prod].dbo.VezaUgovorPartner vup2 
           INNER JOIN [TEST_MaticniPodaci2].[dbo].[Partner] p2 ON vup2.PartnerId = p2.PartnerID 
           WHERE vup2.UgovorId = vup.UgovorId   
           FOR XML PATH('')), 1, 2, '') NUMBER
FROM [TEST_Ugovori_Prod].dbo.VezaUgovorPartner vup 
INNER JOIN [TEST_MaticniPodaci2].[dbo].[Partner] p on vup.PartnerId = p.PartnerID 
GROUP BY vup.UgovorId
ORDER BY vup.UgovorId DESC

[Test blend]