How to avoid duplicates in the STRING_AGG function
Asked Answered
M

3

5

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.

Markova answered 26/2, 2018 at 9:59 Comment(4)
First get the distinct values, then in second query, perform the STRING_AGG or implement custom SQ CLR aggregate - they support distinct.Surakarta
you may need to work out a subquery with nasif deduped and then do the select from it applying string_aggElise
would your please add any example data and result you must wanted.Massa
Use one of the solutions shown here.Ahl
N
6

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 ...
)
Nadeen answered 5/10, 2018 at 14:30 Comment(0)
C
3

I like this format for distinct values: (d is required but you can use any variable name there)

SELECT STRING_AGG(LoadNumber, ',') as LoadNumbers FROM (SELECT DISTINCT LoadNumber FROM [ASN]) d
Compositor answered 11/11, 2020 at 16:18 Comment(0)
G
0

A sample query to remove duplicates while using STRING_AGG().

WITH cte AS (
    SELECT DISTINCT product
    FROM activities
)
SELECT STRING_AGG(product, ',') products
FROM cte;

Or you can use the following query. The result is same -

SELECT STRING_AGG(product, ',') as products
from (
SELECT product
FROM Activities
GROUP BY product
) as _ ;
Grope answered 22/1, 2023 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.