Home > Database > Mysql Tutorial > How to Get Distinct Values Using STRING_AGG in SQL Server?

How to Get Distinct Values Using STRING_AGG in SQL Server?

DDD
Release: 2025-01-03 19:52:40
Original
186 people have browsed it

How to Get Distinct Values Using STRING_AGG in SQL Server?

Distinct Values using STRING_AGG in SQL Server

The STRING_AGG function in SQL Server 2017 allows you to concatenate values into a single string. However, it can return duplicate values when concatenating a field with multiple occurrences.

Consider the following query:

SELECT 
    ProjectID,
    STRING_AGG( newID.value, ',') WITHIN GROUP (ORDER BY newID.value) AS NewField
FROM
    [dbo].[Data] WITH(NOLOCK)  
CROSS APPLY 
    STRING_SPLIT([bID],';') AS newID  
WHERE 
    newID.value IN ('O95833', 'Q96NY7-2')  
GROUP BY 
    ProjectID
ORDER BY 
    ProjectID
Copy after login

This query returns the concatenated values, but duplicates are included:

ProjectID NewField
2 O95833,O95833,O95833,Q96NY7-2,Q96NY7-2,Q96NY7-2
4 Q96NY7-2,Q96NY7-2

To retrieve only unique values, use the DISTINCT keyword in a subquery:

SELECT 
 ProjectID
,STRING_AGG(value, ',') WITHIN GROUP (ORDER BY value) AS 
NewField
FROM (
    SELECT DISTINCT 
      ProjectID
    , newId.value 
    FROM [dbo].[Data] WITH (NOLOCK)  
    CROSS APPLY STRING_SPLIT([bID],';') AS newId  
    WHERE newId.value IN (   'O95833' , 'Q96NY7-2'  )  
) x
GROUP BY ProjectID
ORDER BY ProjectID
Copy after login

This subquery removes duplicates before applying the STRING_AGG function. The final result is:

ProjectID NewField
2 O95833, Q96NY7-2
4 Q96NY7-2

The above is the detailed content of How to Get Distinct Values Using STRING_AGG in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template