Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

T-SQL query that takes json columnar data and displays it in row format

In an Azure SQL database, I have a column that is storing json data.

SELECT a.Response 
FROM [dbo].[Api] a

The result of this query is json in columnar format

{
    "PRODUCT": {
        "0": "a1",
        "1": "a2",
        "2": "a3",
        "3": "a4"
    },
    "STOCK": {
        "0": 3.0,
        "1": 3.0,
        "2": 0.5,
        "3": 6.0
    },
    "SALES": {
        "0": 2487.0,
        "1": 1841.0,
        "2": 391.0,
        "3": 2732.0
    }
}

What I’d like to do is to have a query which displays the above data in SQL row format

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PRODUCT | STOCK | SALES 
--------+-------+------
 a1     | 3.0   | 2487.0
 a2     | 3.0   | 1841.0,
 a3     | 0.5   | 391.0,
 a1     | 6.0   | 2732.0
 

>Solution :

Assuming that the value of the key is the relation, and all keys have a value in all 3 JSON objects, one method would be to use a few calls to OPENJSON and define the relationship in the WHERE:

SELECT P.[value] aS Product,
       St.[value] AS Stock,
       Sa.[value] AS Sales
FROM [dbo].[Api] a
     CROSS APPLY OPENJSON (a.Response, '$.PRODUCT') P
     CROSS APPLY OPENJSON (a.Response, '$.STOCK') St
     CROSS APPLY OPENJSON (a.Response, '$.SALES') Sa
WHERE P.[key] = St.[Key]
  AND St.[Key] = Sa.[Key];

db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading