Search code examples
sqljsonsql-server-2016

Use JSON array in SQL server instead of traditional relational database, each value in 1 row


I have saved the answer values in a table in rows, 1 answer 1 row, 5 rows in this example. If I migrate it to JSON it will be 2 rows(JSON)

Table

Id Optionsid Pid Column
1 2 1 null
2 1 2 null
3 1 2 null
4 2 2 null
5 3 1 null

I want to calculate how many answers(pid) for each Optionsid with

SELECT COUNT(pid)AS Counted, OptionsId
FROM  Answer GROUP BY [Column], OptionsId

Table Results

Counted Optionsid
2 1
2 2
1 3

I have run thus query and saved it in a new table

select * from Answer  for Json Auto

Json Table I added {"answer":} to the Json

id pid json
1 1 {"Answer":[{"Id":1,"Optionsid":2,"Pid":1}]}
2 2 {"Answer":[{"Id":2,"Optionsid":1,"Pid":2},{"Id":2,"Optionsid":1,"Pid":2},{"Id":3,"Optionsid":2,"Pid":2},{"Id":4,"Optionsid":3,"Pid":2}]}

I want to get the same result from Json Table as the Table result above, but I can get it to work This Query only take the first[0] in the array, i want a query who take all values in the array. Can someone help me with this query?

  Select Count(Json_value ([json], '$.Answer[0].Pid')) as Counted,
  Json_value ([json], '$.Answer[0].Optionsid') as OptionsId
  from [PidJson]
  group by Json_value ([json],'$.Answer[0].Column'),Json_value 
  ([json],'$.Answer[0].Optionsid')

Here is a fiddle if you want to see

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=0a2df33717a3917bae699ea3983b70b4


Solution

  • Here is the solution

    SELECT Count(JsonData.Pid)  as Counted,  
    JsonData.Optionsid
    FROM PidJson AS RelationsTab
    CROSS APPLY OPENJSON (RelationsTab.json, 
    N'$.Answer') 
    WITH (
        Pid VARCHAR(200) N'$.Pid',
        Optionsid VARCHAR(200) N'$.Optionsid',
        ColumnValue INT N'$.Column'
       ) AS JsonData
    Group by JsonData.ColumnValue, JsonData.Optionsid
    

    Thanks for your time and that you "force" me to clearify my question and I find the solution