简体   繁体   中英

SQL transform JSON: select one field from json array objects

I have table created with a script

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

where Query column is JSON string like:

[
  {
     "FieldName": "TargetFieldName",
     "Filters": [
       { /* Description Filter 1 */ },
       ...
       { /* Description Filter N */ }
    ]
  }
]

And I'd like to select from that table: Id, Name, and distinct list of column names as json array in THIRD column.

For example for row:

-------------------------------------------------------------------------------------------------
| Id | Name    | Query                                                                          |
-------------------------------------------------------------------------------------------------
| 7  | Query 7 |  [{"FieldName": "A", ... },{ "FieldName": "B" ...},{"FieldName": "B", ... }]   |
-------------------------------------------------------------------------------------------------

I'd like to get

| Id | Name    | DistinctFieldNames |
+----+---------+--------------------+
| 7  | Query 7 |  ["A","B"]         |

My questions are:

  1. Is it possible at all transform json data to other format json data at SQL Server side?
  2. How to write a SQL query to select one field from json array of objects?

Seems like the easiest would be to use a subquery to read the JSON, and the STRING_AGG to create the new one:

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];

You should know that this code only run on SQL Server 2017 and higher version.

SELECT Id,Name,
    (SELECT STRING_AGG(JSON_VALUE(value, '$.FieldName'), ',') As FieldName 
     FROM OPENJSON(Queries.Query)) 
FROM dbo.Queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM