我有包含 Json 的行,例如:
[{"Qty": 1, "Amt": 2.99},{"Qty": 3, Amt": 4.50}]
如何获得每行的 Amt 总和?
复制代码:
DROP TABLE IF EXISTS dbo.SqlQueryResults;
CREATE TABLE dbo.SqlQueryResults(
Id INT,
Result nvarchar(max)
)
GO
INSERT INTO dbo.SqlQueryResults (Id, Result)
VALUES
(1, '[{"Qty":1, "Amt":2.99}, {"Qty":3, "Amt":4.50}]'),
(2, '[{"Qty":2, "Amt":7.99}, {"Qty":5, "Amt":2.50}]')
SELECT * FROM dbo.SqlQueryResults;
我被 Json 路径表达式困住了。文档 JSON 路径表达式 (SQL Server) 仅显示名称为
"people": [{}.{}]
(例如 ex)的数组
这是我现在的疑问:
SELECT Id, SUM(CAST( JSON_VALUE(Result,N'lax $.[].Amt') as decimal))
FROM SqlQueryResults
GROUP BY Id
这是一种方法:
SELECT
id,
sum(cast(JSON_VALUE(value, '$.Amt') as numeric(10,2))) as sum_Amt
FROM dbo.SqlQueryResults
CROSS APPLY OPENJSON(Result)
GROUP BY id