gpt4 book ai didi

Sql查询获取json结果中没有列名的数组

转载 作者:行者123 更新时间:2023-12-02 20:36:21 25 4
gpt4 key购买 nike

我有一个包含以下字段的表格

 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<> fiddle here

关于Sql查询获取json结果中没有列名的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com