我工作的一个查询,将收集从表中的数据和显示报表数据。
数据是这样的:
Player Score
001 10
001 20
002 20
002 20
001 10
002 10
003 20
002 20
001 10
我希望它这样显示出来
Player Score
001 10,20
002 10,20
003 20
但我得到的是所有的数据在这样的得分列组合列表
Player Score
001 10,20,10,10
002 20,20,10,20
003 20
有没有人有一个想法如何使这项工作?
对于SQL Server,你可以使用:
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
有点晚了,并稍微偏离主题为另一个RDBMS,但我发现这个线索寻找一个解决方案,在Postgres的这个问题。 我发现一个,所以如果其他人需要在PG来解决这个问题:
SELECT string_agg(DISTINCT <column>,'delimiter') FROM <table> GROUP BY <column2>
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