在Microsoft SQL中解析JSON

问题描述 投票:0回答:2

我有以下JSON,而且我不知道如何解析“值”(在SQL中运行时,您会获得3列键,值和类型)

有什么想法吗?

       DECLARE @json NVARCHAR(MAX);
SET @json = N'[
  {"salesDate":"2020-03-02","storeSales":[
{"storeId":"104","sales":[
{"productId":"20002","salesVolume":0.700,"salesQuantity":2,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"74301","salesVolume":0.750,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"642401","salesVolume":0.750,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"784001","salesVolume":2.100,"salesQuantity":3,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"1013801","salesVolume":1.500,"salesQuantity":2,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"1202801","salesVolume":0.750,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"1209901","salesVolume":0.700,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"1282201","salesVolume":0.750,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"3317301","salesVolume":1.500,"salesQuantity":2,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"4801301","salesVolume":0.700,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"5780106","salesVolume":6.000,"salesQuantity":2,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"7964902","salesVolume":0.375,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"10785001","salesVolume":0.750,"salesQuantity":1,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}},
{"productId":"11037501","salesVolume":1.500,"salesQuantity":2,"lastChanged":{"date":"2020-03-03","time":"07:28:06"}}]}]}]';

SELECT *
FROM OPENJSON(@json)

“

json sql-server parsing
2个回答
3
投票

假设您想获取销售数据,请尝试此操作(尽管我不确定100%是否此查询提供最佳性能)

SELECT [SalesDate], [StoreId], [ProductId], [SalesVolume], [SalesQuantity]
FROM OPENJSON(@json) WITH (
        [SalesDate] DATETIME '$.salesDate',
        [StoreSales] NVARCHAR(MAX) '$.storeSales' AS JSON
    )
    OUTER APPLY OPENJSON(StoreSales) WITH (
        [StoreId] INT '$.storeId',
        [Sales] NVARCHAR(MAX) '$.sales' AS JSON
    )
    OUTER APPLY OPENJSON(Sales) WITH (
        [ProductId] INT '$.productId',
        [SalesVolume] DECIMAL(18, 4) '$.salesVolume',
        [SalesQuantity] INT '$.salesQuantity'
    )

0
投票

Value是JSON数组中的第一个对象,它本身也是另一个JSON对象。因此,您将不得不使用其他SQL Server JSON实用程序来阅读它。例如:

SELECT JSON_VALUE(Value, '$.salesDate')
FROM OPENJSON(@json)
© www.soinside.com 2019 - 2024. All rights reserved.