简体   繁体   English

与 JSON 数组交叉应用

[英]Cross apply with JSON array

I have table stored data is in below format -我有表格存储的数据格式如下 -

在此处输入图片说明

Now, I want to write a SQL query to represent this data in below format-现在,我想编写一个 SQL 查询来表示以下格式的数据 -

在此处输入图片说明

Note: Data stored in Product column is JSON array.注意:Product 列中存储的数据是 JSON 数组。

You need two additional APPLY operators with two different OPENJSON() calls.您需要两个具有两个不同OPENJSON()调用的额外APPLY运算符。 First call is with default schema and the result is a table with columns key , value and type .第一次调用使用默认架构,结果是一个包含keyvaluetype列的表。 The second call is with explicit schema with the appropriate columns, defined using the WITH clause:第二个调用是使用带有适当列的显式架构,使用WITH子句定义:

Table:桌子:

Table:桌子:

CREATE TABLE Data (
   CustomerID int,
   City nvarchar(50),
   Product nvarchar(max)
)
INSERT INTO Data
   (CustomerID, City, Product)
VALUES
   (1, N'Delhi', N'[{"Products": [{"Id": "1", "Name": "TV"}, {"Id": "2", "Name": "Laptop"}]}]'),
   (2, N'Bamgalore', N'[{"Products": [{"Id": "1", "Name": "TV"}, {"Id": "2", "Name": "Laptop"}, {"Id": "3", "Name": "Mobile"}]}]')

Statement:陈述:

SELECT d.CustomerID, j2.Id, j2.Name
FROM Data d
CROSS APPLY OPENJSON(d.Product, '$') j1
CROSS APPLY OPENJSON(j1.[value], '$.Products') WITH (
   Id nvarchar(10) '$.Id',
   Name nvarchar(50) '$.Name'
) j2

Result:结果:

----------------------
CustomerID  Id  Name
----------------------
1           1   TV
1           2   Laptop
2           1   TV
2           2   Laptop
2           3   Mobile

You can apply the arrays, to get to the object values.您可以应用数组来获取对象值。

SELECT t.CustomerId, a.*
FROM YourCustomerProductsTable t
OUTER APPLY
(
   SELECT
     [ProductId] = CAST(JSON_VALUE(obj.value,'$.Id') AS INT)
   , [Product] = JSON_VALUE(obj.value,'$.Name')
   FROM OPENJSON(t.Product) AS arr
   CROSS APPLY OPENJSON(arr.value, '$.Products') AS obj
) a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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