Do you have a comment or suggestion to improve SQL Server? We’d love to hear it!

Support TOP for STRING_AGG

Currently STRING_AGG aggregates all strings passed as an input. It would be very useful to support TOP x values. It would be very good when we want to return only x number values associated to a lookup value(s)

Example:

CREATE TABLE dbo.Test (a VARCHAR(255),b VARCHAR(255))
INSERT INTO dbo.Test (a,b)
VALUES('A','Str1')
,('A','Str2')
,('A','Str3')
,('A','Str4')
,('A','Str5')

SELECT STRING_AGG(TOP 3 b, ',') WITHIN GROUP (ORDER BY b) FROM dbo.Test GROUP BY a

It returns: 'Str1,Str2,Str3'

7 votes
Sign in
(thinking…)
Sign in with: oidc
Signed in as (Sign out)

We’ll send you updates on this idea

Visakh Murukesan shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

0 comments

Sign in
(thinking…)
Sign in with: oidc
Signed in as (Sign out)
Submitting...

Feedback and Knowledge Base