0

I tried to return the queryset with one field which is the list string in django, for example, like this:

Name:
Chicken Wing            
Ids:
2529,2695,10829,10995,12129,12295  

I only know how to get the queryset by GROUP_CONCAT which support MySQL database, when I migrated to SQL Server 2017 database. It doesn't work, I checked SQL Server 2017 support STRING_AGG, but I don't know how to use it in django. (I am using django rest framework).

Can anyone can help me?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Ellie
  • 1
  • 1

1 Answers1

0

You can use STUFF function for getting expected output.

create table  #temp(
id int,
name varchar(20)
)

insert into #temp
select 1, 'abc'
union 
select 2, 'abc'
union 
select 3, 'abc'
union
select 4, 'xyz'
union 
select 5, 'xyz'
union 
select 6, 'xyz'

SELECT distinct m.name as name,
 STUFF((
          SELECT ',' + cast(te.id as varchar(50))
          FROM #temp te
          WHERE t.name = te.name
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM #temp t
Anagha
  • 918
  • 1
  • 8
  • 17