簡體   English   中英

將 JSON 數組項提取到以逗號分隔的單個列

[英]Extract a JSON array items to a single column separated with comma

努力尋找以下 JSON 問題的答案。 我想用逗號分隔值將"shipmentItems"數組中的整個SKU/Quantity列表顯示到它們各自的列中。 下面的示例僅允許我顯示數組中的第一個 SKU/數量,但我的目標是讓所有列中以逗號分隔。

JSON 示例:

{"shipments": [
    {
        "shipmentId": 100003768,
        "orderNumber": "9648219086",
        "shipDate": "2021-10-28",
        "serviceCode": "ups_ground",
        "shipmentItems": [
            {
                "orderItemId": 1464643208,
                "lineItemKey": "10322938560608",
                "sku": "SCPXTSS-BAG-06",
                "name": "SCOOP-PLATE-06 (1000ml)",
                "weight": {
                    "value": 0,
                    "units": "ounces",
                    "WeightUnits": 1
                },
                "quantity": 1,
                "unitPrice": 0,
                "taxAmount": null
                },
            {
                "orderItemId": 1464643207,
                "lineItemKey": "10322938527840",
                "sku": "SCPZRTS-TRAY-01",
                "name": "Beef: Tray 3 (Fill 004)<br>",
                "weight": {
                    "value": 60,
                    "units": "ounces",
                    "WeightUnits": 1
                },
                "quantity": 1,
                "unitPrice": 102.72,
                "taxAmount": null
                }
        ],
        "labelData": null,
        "formData": null
    }
 
]
}

我正在使用的 SQL 查詢:

DECLARE @JSON varchar(max)

SELECT @JSON = BulkColumn
FROM OPENROWSET (BULK 'C:\Users\XPS-LT\json\today\shipments_20211031.json', SINGLE_CLOB)
IMPORT
SELECT *
FROM OPENJSON (@JSON, '$.shipments') 
WITH 
(
    [shipmentId] bigint, 
    [orderNumber] nvarchar(60), 
    [shipDate] date, 
    [serviceCode] nvarchar(30), 
    [sku] nvarchar(MAX) N'$.shipmentItems[0].sku',
    [quantity] int N'$.shipmentItems[0].quantity' 
)          
;

當前結果

輸入 JSON 的"shipmentItems"部分是一個數組,因此您需要在第一個顯式模式中添加一個AS JSON子句和一個額外的OPENJSON()調用:

DECLARE @json nvarchar(max)
...

SELECT 
   j.[shipmentId], j.[orderNumber], j.[shipDate], j.[serviceCode],
   a.[sku], a.[quantity]
FROM OPENJSON (@json, '$.shipments') WITH (
   [shipmentId] bigint, 
   [orderNumber] nvarchar(60), 
   [shipDate] date, 
   [serviceCode] nvarchar(30), 
   [shipmentItems] nvarchar(max) AS JSON 
) j         
OUTER APPLY (
   SELECT 
      STRING_AGG([sku], ',') WITHIN GROUP (ORDER BY [orderItemId]),
      STRING_AGG([quantity], ',') WITHIN GROUP (ORDER BY [orderItemId])
   FROM OPENJSON (j.shipmentItems) WITH (
      [orderItemId] int '$.orderItemId',
      [sku] nvarchar(max) '$.sku',
      [quantity] int N'$.quantity' 
   )    
) a ([sku], [quantity])

結果:

shipmentId orderNumber shipDate   serviceCode sku                            quantity
100003768  9648219086  2021-10-28 ups_ground  SCPZRTS-TRAY-01,SCPXTSS-BAG-06 1,1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM