0

我尝试使用一个字段返回查询集,该字段是 django 中的列表字符串,例如,如下所示:

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

GROUP_CONCAT当我迁移到 SQL Server 2017 数据库时,我只知道如何获取支持 MySQL 数据库的查询集。它不起作用,我检查了 SQL Server 2017 支持STRING_AGG,但我不知道如何在 django 中使用它。(我正在使用 django rest 框架)。

谁能帮助我?

4

1 回答 1

0

您可以使用STUFF函数来获得预期的输出。

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
于 2019-11-26T07:17:44.990 回答