我有一个包含以下字段的表格
Id RequestId CategoryId
1 112 1
2 123 1
3 123 2
SELECT R.RequestId,
(SELECT RC.CategoryId FROM Request RC WHERE RC.Id = R.Id FOR JSON AUTO) AS Categories
FROM Request R
上面的查询返回如下所述的数据
RequestId Categories
112 [{"CategoryId":"1"}]
123 [{"CategoryId":"1"},{"CategoryId":"2"}]
但是,我希望不应该为json数组中的每个项重复列名称CategoryId。因此,我的预期结果是:
RequestId Categories
112 ["1"]
123 ["1","2"]
用过:SQL to JSON - array of objects to array of values in SQL 2016
create table Request ( Id int, RequestId int, CategoryId int ) GO
insert into Request (Id,RequestId,CategoryId) values ( 1, 112, 1), ( 2, 123, 1), ( 3, 123, 2); GO
SELECT distinct R.RequestId, ( SELECT JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + convert(varchar(10), RC.CategoryId) + '"' FROM Request RC WHERE RC.RequestId = R.RequestId FOR XML PATH('')),1,1,'') + ']' ) Categories FOR JSON PATH , WITHOUT_ARRAY_WRAPPER ) AS Categories FROM Request R GO
RequestId | Categories --------: | :----------------------- 112 | {"Categories":["1"]} 123 | {"Categories":["1","2"]}
SELECT distinct R.RequestId, JSON_QUERY( ( SELECT JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + convert(varchar(10), RC.CategoryId) + '"' FROM Request RC WHERE RC.RequestId = R.RequestId FOR XML PATH('')),1,1,'') + ']' ) Categories FOR JSON PATH , WITHOUT_ARRAY_WRAPPER ) , '$.Categories' ) FROM Request R GO
RequestId | (No column name) --------: | :--------------- 112 | ["1"] 123 | ["1","2"]
db <>小提琴here
可以使用REPLACE实现:
declare @test table ([Id] int, [RequestId] int, [CategoryId] int)
insert into @test values
(1, 112, 1)
, (2, 123, 1)
, (3, 123, 2)
SELECT R.RequestId,
json_query(replace(replace((SELECT RC.CategoryId FROM @test RC WHERE RC.Id = R.Id FOR JSON AUTO), '{"CategoryId":', '"'), '}','"')) AS Categories
FROM @test R
据我所知,你需要自己聚合字符串,然后将其转换为json。例如,在Sql Server 2017中,您可以使用STRING_AGG
:
select
t.RequestId,
concat('[',string_agg(t.CategoryId, ','),']') as Categories
from Table1 as t
group by
t.RequestId
如果您需要将数组值设置为字符串而不是整数,则可以手动添加"
字符,并且您可能还需要使用STRING_ESCAPE
以便安全地转换特殊字符:
select
t.RequestId,
concat('[',string_agg(concat('"', string_escape(t.CategoryId, 'json'),'"'),','),']') as Categories
from Table1 as t
group by
t.RequestId
在早期版本的Sql Server中,您可以使用xml技巧或创建自定义clr聚合。