How to avoid duplicates in the STRING_AGG function

☆樱花仙子☆ 提交于 2019-12-01 05:40:07

问题


My query is below:

select 
    u.Id,
    STRING_AGG(sf.Naziv, ', ') as 'Ustrojstvena jedinica',
    ISNULL(CONVERT(varchar(200), (STRING_AGG(TRIM(p.Naziv), ', ')), 121), '') 
    as 'Partner',

from Ugovor as u

        left join VezaUgovorPartner as vup
            on vup.UgovorId = u.Id AND vup.IsDeleted = 'false'
        left join [TEST_MaticniPodaci2].dbo.Partner as p
            on p.PartnerID = vup.PartnerId
        left join [dbo].[VezaUgovorUstrojstvenaJedinica] as vuu
            on vuu.UgovorId = u.Id
        left join [TEST_MaticniPodaci2].hcphs.SifZavod as sf
            on sf.Id = vuu.UstrojstvenaJedinicaId
        left join [dbo].[SifVrstaUgovora] as vu
            on u.VrstaUgovoraId = vu.Id

  group by u.Id, sf.Naziv

My problem is that I can have more sf.Naziv and also only one sf.Naziv so I have to check if there is one and then show only one result and if there is two or more to show more results. But for now the problem is when I have only one sf.Naziv, query returns two sf.Naziv with the same name because in first STRING_AGG i have more records about p.Naziv.

I have no idea how to implement DISTINCT into STRING_AGG function

Any other solutions are welcome, but I think it should work with DISTINCT function.


回答1:


It looks like distinct won't work, so what you should do is put your whole query in a subquery, remove the duplicates there, then do STRING_AGG on the data that has no duplicates.

SELECT STRING_AGG(data)
FROM (
   SELECT DISTINCT FROM ...
)


来源:https://stackoverflow.com/questions/48985732/how-to-avoid-duplicates-in-the-string-agg-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!