交叉应用 OPENJSON 获取 2D 数据

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

我有来自 3 个通道的传感器的数据,每 10 分钟测量一次 - 数据在表格的一列中以 JSON 形式给出。

对于每个时间戳 ts,有 3 个 YValues 作为数组(Intensity-Values),相应的 XValues(XAxis_nm)也作为数组给出

JSON - 一列条目的示例(假设列名称是 colJsonText:

{“ts”:“2024-04-17T10:10:00”,“强度”:[101, 102, 103],“XAxis_nm”:[410, 420, 430]}

现在我想查询JSON数据,结果如下: desired result

我尝试了以下查询(我已将 2 行 colJson 的示例数据直接添加到查询中,以便轻松重现:

SELECT ts, Intensity, XAxis_nm FROM OPENJSON('[{"ts": "2024-04-17T10:10:00", "Intensities": [101, 102, 103], "XAxis_nm": [410, 420, 430]}, {"ts": "2024-04-17T10:20:00", "Intensities": [201, 202, 203], "XAxis_nm": [410, 420, 430]}]') WITH (ts nvarchar(32), Intensities NVARCHAR(MAX) AS JSON, XAxis_nm NVARCHAR(MAX) AS JSON) AS a CROSS APPLY OPENJSON (a.Intensities) WITH (Intensity INT '$')

结果如下:

result of query

如何才能只获得相应的 XAxis-Value 而不是每行的整个 XAxis_nm,如图“所需结果”所示?

arrays json 2d cross-apply
1个回答
0
投票

我不清楚你想看到什么,所以我创建了 3 组的示例


DECLARE @t TABLE (id INT IDENTITY(1,1) not null, rawjson nvarchar(2000) NULL)
INSERT INTO @t VALUES
('[{"ts": "2024-04-17T10:10:00", "Intensities": [101, 102, 103], "XAxis_nm": [410, 420, 430]}, {"ts": "2024-04-17T10:20:00", "Intensities": [201, 202, 203], "XAxis_nm": [410, 420, 430]}]')

SELECT 
    ts
    ,JSON_VALUE(XAxis_nm, '$[0]') AS XAxis1
    ,JSON_VALUE(Intensities, '$[0]') AS Intensity1

    ,JSON_VALUE(XAxis_nm, '$[1]') AS XAxis2
    ,JSON_VALUE(Intensities, '$[1]') AS Intensity2

    ,JSON_VALUE(XAxis_nm, '$[2]') AS XAxis3
    ,JSON_VALUE(Intensities, '$[2]') AS Intensity3
FROM @t t
CROSS APPLY OPENJSON(t.rawjson) WITH (
            ts nvarchar(32), 
            Intensities NVARCHAR(MAX) AS JSON, 
            XAxis_nm nvarchar(max) as json)
--CROSS APPLY OPENJSON (Intensities) WITH (Intensity INT '$')
--outer APPLY OPENJSON (XAxis_nm) WITH (XAxis INT '$')



结果将是:

ts X轴1 强度1 X轴2 强度2 X轴3 强度3
2024-04-17T10:10:00 410 101 420 102 430 103
2024-04-17T10:20:00 410 201 420 202 430 203
© www.soinside.com 2019 - 2024. All rights reserved.