我需要JSON数组中的所有值

时间:2019-04-02 14:05:28

标签: sql json sql-server

我有一个表,其中有JSON数据,字段类型为NVARCHAR(4000)

    [
        {"number":1,"booked":0},
        {"number":2,"booked":0},
        {"number":3,"booked":0},
        {"number":4,"booked":1},
        {"number":5,"booked":0},
        {"number":6,"booked":0},
        {"number":7,"booked":0},
        {"number":8,"booked":0}
    ]

我想查询该数组的字段,并希望预订数为1而未预订的输出为7。 我已经使用了JSON_VALUE()JSON_QUERY()函数,但并没有抓住重点。

我也希望预订Number:4。

我正在使用SQL Server 2016

2 个答案:

答案 0 :(得分:1)

嗨,如果我了解您要尝试做的所有事情,那么这些示例可以回答:

DECLARE @json NVARCHAR(MAX)
SET @json =  
N'[  
       {"number":1,"booked":0},
        {"number":2,"booked":0},
        {"number":3,"booked":0},
        {"number":4,"booked":1},
        {"number":5,"booked":0},
        {"number":6,"booked":0},
        {"number":7,"booked":0},
        {"number":8,"booked":0}
 ]'  

 SELECT number, booked
FROM OPENJSON(@json) 
    WITH (number int 'strict $.number', booked int   'strict $.booked')
WHERE booked = 1

在未来的提议中,请提供一些数据和例外的输出,并查询您要尝试的内容。

答案 1 :(得分:0)

    [
        {"number":1,"booked":0},
        {"number":2,"booked":0},
        {"number":3,"booked":0},
        {"number":4,"booked":1},
        {"number":5,"booked":0},
        {"number":6,"booked":0},
        {"number":7,"booked":0},
        {"number":8,"booked":0}
    ]

选择查询:

SELECT 
 COUNT(JSON_VALUE(jsonInfo,'$.booked')) 
 OVER(PARTITION BY JSON_VALUE(jsonInfo,'$.booked'))
FROM table
GROUP BY JSON_VALUE(jsonInfo,'$.booked')
ORDER BY JSON_VALUE(jsonInfo,'$.booked')