JSON_ARRAYAGG (Transact-SQL)
适用于:Azure SQL 数据库
通过聚合 SQL 数据或列来构造 JSON 数组。
若要改为通过聚合来创建 JSON 对象,请使用 JSON_OBJECTAGG。
注意
目前,json 聚合函数 JSON_OBJECTAGG
和 JSON_ARRAYAGG
的预览版都可用于 Azure SQL 数据库。
语法
JSON_ARRAYAGG (value_expression [ order_by_clause ] [ json_null_clause ] )
json_null_clause ::= NULL ON NULL | ABSENT ON NULL
order_by_clause ::= ORDER BY <column_list>
参数
value_expression
值表达式可以是列或查询或常量/文本中的表达式。
json_null_clause
可选。 json_null_clause 可用于控制 JSON_ARRAYAGG
函数在 value_expression 为 NULL
时的行为。 在生成 JSON 数组中的元素值时,选项 NULL ON NULL
将 SQL NULL
值转换为 JSON null 值。 如果值为 ABSENT ON NULL
,选项 NULL
将省略 JSON 数组中的元素。 如果省略,则 ABSENT ON NULL
为默认值。
order_by_clause
可选。 可以指定所生成 JSON 数组中的元素顺序,以便对输入的行进行排序,从而实现聚合。
示例
示例 1
以下示例返回空 JSON 数组。
SELECT JSON_ARRAYAGG(null);
结果
[]
示例 2
以下示例构建具有三个来自结果集的元素的 JSON 数组。
SELECT JSON_ARRAYAGG( c1 )
FROM (
VALUES ('c'), ('b'), ('a')
) AS t(c1);
Result
["c","b","a"]
示例 3
以下示例将构造一个 JSON 数组,其中包含三个按列值排序的元素。
SELECT JSON_ARRAYAGG( c1 ORDER BY c1)
FROM (
VALUES ('c'), ('b'), ('a')
) AS t(c1);
Result
["a","b","c"]
示例 4
以下示例返回包含两列的结果。 第一列包含 object_id
值。 第二列包含一个 JSON 数组,其中包含列的名称。 JSON 数组中的列根据 column_id
值进行排序。
SELECT TOP(5) c.object_id, JSON_ARRAYAGG(c.name ORDER BY c.column_id) AS column_list
FROM sys.columns AS c
GROUP BY c.object_id;
Result
object_id | column_list |
---|---|
3 | ["rsid","rscolid","hbcolid","rcmodified","ti","cid","ordkey","maxinrowlen","status","offset","nullbit","bitpos","colguid","ordlock"] |
5 | ["rowsetid","ownertype","idmajor","idminor","numpart","status","fgidfs","rcrows","cmprlevel","fillfact","maxnullbit","maxleaf","maxint","minleaf","minint","rsguid","lockres","scope_id"] |
6 | ["id","subid","partid","version","segid","cloneid","rowsetid","dbfragid","status"] |
7 | ["auid","type","ownerid","status","fgid","pgfirst","pgroot","pgfirstiam","pcused","pcdata","pcreserved"] |
8 | ["status","fileid","name","filename"] |