简体   繁体   English

SQL Server查询JSONobject以获取聚合值

[英]SQL Server query JSONobject to get aggregated values

I have a JSON object stored in SQL Server, in a nvarchar(max) column. 我在nvarchar(max)列中有一个存储在SQL Server中的JSON对象。 The JSON looks like this: JSON如下所示:

{
"data": [{
        "RespID": 3512,
        "ObsPriceValue": 2.34
    }, {
        "RespID": 4904,
        "ObsPriceValue": 2.54
    }, {
        "RespID": 5127,
        "ObsPriceValue": 3.44
    }]
}

The above example array is made up of three items, but I don't know how many items are present in the record, and they can be 2 as well as up to 30. 上面的示例数组由三个项目组成,但是我不知道记录中有多少个项目,它们可以是2个,也可以是30个。

Each row in the table has an object like the above. 表格中的每一行都有一个类似于上述的对象。

I'd like to get, in a single query, the average value of the field ObsPriceValue 我想在一个查询中获得字段ObsPriceValue的平均值

I've tried with JSON_QUERY , but I have always to specify the index of the element. 我尝试使用JSON_QUERY ,但是我总是必须指定元素的索引。

Is there a way to get it or the JSON schema the data is stored is wrong? 有没有办法获取它,或者存储数据的JSON模式是错误的?

Next approach may help. 下一种方法可能会有所帮助。 You need to use OPENJSON() with explicit schema definition to return a table with ObsPriceValue column: 您需要使用带有显式架构定义的OPENJSON()来返回包含ObsPriceValue列的表:

JSON: JSON:

DECLARE @json nvarchar(max) = N'{"data": [{
        "RespID": 3512,
        "ObsPriceValue": 2.34
    }, {
        "RespID": 4904,
        "ObsPriceValue": 2.54
    }, {
        "RespID": 5127,
        "ObsPriceValue": 3.44
    }]
}'

Statement: 声明:

SELECT AVG(ObsPriceValue) AS AvgObsPriceValue
FROM OPENJSON(@json, '$.data') WITH (
   ObsPriceValue numeric(10, 2) '$.ObsPriceValue' 
) j 

Output: 输出:

----------------
AvgObsPriceValue
----------------
2.773333

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

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