我有一个存储在SQL服务器中的Json数据:
{
"group":{
"operator":"AND",
"rules":[
{
"condition":"=",
"field":"F1",
"table":"ATT",
"data":"TEST",
"readOnly":false,
"hidden":false,
"$$hashKey":"005"
},
{
"condition":"=",
"field":"CLASS",
"table":"OBJ",
"data":"A1",
"readOnly":false,
"hidden":false,
"$$hashKey":"008"
},
{
"group":{
"operator":"AND",
"rules":[
{
"condition":"=",
"field":"F1",
"table":"ATT",
"data":"TEST2",
"readOnly":false,
"hidden":false,
"$$hashKey":"00D"
},
{
"condition":"=",
"field":"F1",
"table":"ATT",
"data":"TEST3",
"readOnly":false,
"hidden":false,
"$$hashKey":"00G"
}
]
},
"table":"",
"$$hashKey":"009"
}
]
}
}
如何使用SQL获取值为F1
的元素字段的计数?
答案 0 :(得分:0)
试试这个 - >
Select Count(*)
From mytable
WHERE JSON_VALUE(Serialized, '$.field')="F1"
答案 1 :(得分:0)
作为建议,JSON数据不应该自行存储。您应根据要存储的数据创建表和列。也许创建一个名为group的数据库,使用一个名为operator的表,它有三列,运算符,规则和规则值。所以它看起来像这样:
Operator Rule RuleValue
-------- ----------- ---------
| #1 | condition | = |
| #1 | field | f1 |
| #1 | table | ATT |
| #2 | data | test |
您可以根据需要更改表,但请记住JSON和XML是一种在文件中存储数据的方法。因此,在将数据存储在数据库中时,您不应将其存储在XMl或JSON
中答案 2 :(得分:0)
DECLARE @json NVARCHAR(MAX) = '{"group":{
"operator":"AND",
"rules":
[{"condition":"=",
"field":"F1",
"table":"ATT",
"data":"TEST",
"readOnly":false,
"hidden":false,
"$$hashKey":"005"},
{"condition":"=",
"field":"BANKID",
"table":"ATT",
"data":"A1",
"readOnly":false,
"hidden":false,
"$$hashKey":"008"}]}}';
SELECT COUNT(*)
FROM OPENJSON(@json, '$.group.rules')
WHERE JSON_VALUE(value, '$.field') = 'F1'
你说有桌子吗? CROSS APPLY
是你的朋友:
SELECT T.[data], rules.F1_count
FROM T CROSS APPLY (
SELECT COUNT(*) AS F1_count
FROM OPENJSON(jsonData, '$.group.rules')
WHERE JSON_VALUE(value, '$.field') = 'F1'
) AS rules