Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross apply with JSON array

I have table stored data is in below format -

enter image description here

Now, I want to write a SQL query to represent this data in below format-

enter image description here

Note: Data stored in Product column is JSON array.

like image 598
user1694660 Avatar asked Jun 05 '26 17:06

user1694660


1 Answers

You need two additional APPLY operators with two different OPENJSON() calls. First call is with default schema and the result is a table with columns key, value and type. The second call is with explicit schema with the appropriate columns, defined using the WITH clause:

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
like image 148
Zhorov Avatar answered Jun 07 '26 07:06

Zhorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!