Get unique values using STRING_AGG in SQL Server

后端 未结 4 1293
情话喂你
情话喂你 2020-12-20 11:55

The following query returns the results shown below:

SELECT 
    ProjectID, newID.value
FROM 
    [dbo].[Data] WITH(NOLOCK)  
CROSS APPLY 
    STRING_SPLIT([         


        
4条回答
  •  萌比男神i
    2020-12-20 12:06

    You can make a distinct view of the table, that holds the aggregate values, that is even simpler:

    Create Table Test (field1 varchar(1), field2 varchar(1));
    
    go
    
    Create View DistinctTest as (Select distinct field1, field2 from test group by field1,field2);
    
    go
    
    insert into Test Select 'A', '1';
    insert into Test Select 'A', '2';
    insert into Test Select 'A', '2';
    insert into Test Select 'A', '2';
    insert into Test Select 'D', '1';
    insert into Test Select 'D', '1';
    
    select string_agg(field1, ',')  from Test where field2 = '1';  /* duplicates: A,D,D */;
    
    select string_agg(field1, ',')  from DistinctTest where field2 = '1';  /* no duplicates: A,D  */;
    

提交回复
热议问题