我已使用脚本创建了表
CREATE TABLE [dbo].[Queries]
(
[Id] [INT] NOT NULL,
[Name] [NVARCHAR](MAX) NOT NULL,
[Module] [NCHAR](64) NOT NULL,
[Query] [NVARCHAR](MAX) NOT NULL,
PRIMARY KEY (Id)
)
GO
其中Query
列是JSON字符串,例如:
[
{
"FieldName": "TargetFieldName",
"Filters": [
{ /* Description Filter 1 */ },
...
{ /* Description Filter N */ }
]
}
]
我想从该表中进行选择:Id,名称, 以及列名称的不同列表,如 THIRD 中的json数组 列。
例如用于行:
-------------------------------------------------------------------------------------------------
| Id | Name | Query |
-------------------------------------------------------------------------------------------------
| 7 | Query 7 | [{"FieldName": "A", ... },{ "FieldName": "B" ...},{"FieldName": "B", ... }] |
-------------------------------------------------------------------------------------------------
我想得到
| Id | Name | DistinctFieldNames |
+----+---------+--------------------+
| 7 | Query 7 | ["A","B"] |
我的问题是:
答案 0 :(得分:1)
似乎最简单的方法是使用子查询读取JSON,然后使用STRING_AGG
创建新的JSON:
SELECT V.ID,
V.Name,
'[' + STRING_AGG('"' + ca.FieldName + '"',',') WITHIN GROUP (ORDER BY ca.FieldName) + ']'
FROM (VALUES(7,'Query 7','[{"FieldName": "A"},{ "FieldName": "B"},{"FieldName": "B"}]'))V(ID,[Name], Query)
CROSS APPLY (SELECT DISTINCT OJ.FieldName
FROM OPENJSON (V.Query)
WITH (FieldName char(1)) OJ) ca --May need larger size, char(1) based on your sample data
GROUP BY V.ID,
V.[Name];
答案 1 :(得分:1)
您应该知道此代码仅在SQL Server 2017和更高版本上运行。
SELECT Id,Name,
(SELECT STRING_AGG(JSON_VALUE(value, '$.FieldName'), ',') As FieldName
FROM OPENJSON(Queries.Query))
FROM dbo.Queries