Merge multiple rows into one column without duplicates

后端 未结 4 730
轻奢々
轻奢々 2021-02-01 02:44

I am working on a query that will collect data from a table and display the data for a report.

The data looks like this:

Player Score
001      10
001           


        
相关标签:
4条回答
  • 2021-02-01 03:27
    UPDATE AllNews 
        SET ArticleSource = pp.[NewsText]
      FROM AllNews AS an
      INNER JOIN (  select t1.Id,
      stuff((SELECT distinct '.' + t2.[Text]
               FROM NewsPhotos t2
               where t2.NewsId = t1.Id
               FOR XML PATH('')),1,1,'') as [NewsText]
                 from AllNews t1
                 group by t1.Id) as pp
      ON pp.Id = an.Id
    
    0 讨论(0)
  • 2021-02-01 03:29

    A bit late and slightly off-topic as for another RDBMS, but I found this thread searching for a solution to this problem in Postgres. I found one, so if anyone else needs to solve this problem in Pg:

    SELECT string_agg(DISTINCT <column>,'delimiter') FROM <table> GROUP BY <column2>
    
    0 讨论(0)
  • 2021-02-01 03:44

    For SQL Server you can use:

    select player,
      stuff((SELECT distinct ', ' + cast(score as varchar(10))
               FROM yourtable t2
               where t2.player = t1.player
               FOR XML PATH('')),1,1,'') 
    from yourtable t1
    group by player
    
    0 讨论(0)
  • 2021-02-01 03:45

    Previous accepted answer is superseded in SQL 2017 and up by STRING_AGG:

    SELECT Player, STRING_AGG(Score,', ') FROM YourTable GROUP BY Player
    

    No need to use awkward FOR XML syntax.

    I ran this and the accepted answer side-by-side on 100K rows. Accepted answer took 90 seconds, the STRING_AGG version takes less than 1 second.

    0 讨论(0)
提交回复
热议问题