SQL Server openjson
Posted
技术标签:
【中文标题】SQL Server openjson【英文标题】: 【发布时间】:2020-05-17 12:01:18 【问题描述】:从我的 json 数据中,我需要这样的结果:我想获得两列距离和持续时间 - 谁能帮忙?
"distances": [
[0, 6136.2, 6136.2, 0],
[4704.7, 0, 0, 4704.7],
[4704.7, 0, 0, 4704.7],
[0, 6136.2, 6136.2, 0]
],
"durations": [
[0, 554.5, 554.5, 0],
[446.4, 0, 0, 446.4],
[446.4, 0, 0, 446.4],
[0, 554.5, 554.5, 0]
]
【问题讨论】:
像什么?你的尝试有什么不奏效的? 【参考方案1】:这是一种方法
DECLARE @Json NVARCHAR(MAX) = N'
"distances": [
[0, 6136.2, 6136.2, 0],
[4704.7, 0, 0, 4704.7],
[4704.7, 0, 0, 4704.7],
[0, 6136.2, 6136.2, 0]
],
"durations": [
[0, 554.5, 554.5, 0],
[446.4, 0, 0, 446.4],
[446.4, 0, 0, 446.4],
[0, 554.5, 554.5, 0]
]
'
SELECT CA.distance,
CA.duration,
dist1.[key] AS OuterArrayIndex,
CA.[key] AS InnerArrayIndex
FROM OPENJSON(JSON_QUERY(@Json, '$.distances')) dist1
JOIN OPENJSON(JSON_QUERY(@Json, '$.durations')) dur1
ON dist1.[key] = dur1.[key]
CROSS APPLY
(
SELECT dist2.value AS distance,
dur2.value AS duration,
dist2.[key]
FROM OPENJSON(dist1.value) dist2
JOIN OPENJSON(dur1.value) dur2
ON dist2.[key] = dur2.[key]
)CA
ORDER BY OuterArrayIndex,
InnerArrayIndex
返回
+----------+----------+-----------------+-----------------+
| distance | duration | OuterArrayIndex | InnerArrayIndex |
+----------+----------+-----------------+-----------------+
| 0 | 0 | 0 | 0 |
| 6136.2 | 554.5 | 0 | 1 |
| 6136.2 | 554.5 | 0 | 2 |
| 0 | 0 | 0 | 3 |
| 4704.7 | 446.4 | 1 | 0 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 2 |
| 4704.7 | 446.4 | 1 | 3 |
| 4704.7 | 446.4 | 2 | 0 |
| 0 | 0 | 2 | 1 |
| 0 | 0 | 2 | 2 |
| 4704.7 | 446.4 | 2 | 3 |
| 0 | 0 | 3 | 0 |
| 6136.2 | 554.5 | 3 | 1 |
| 6136.2 | 554.5 | 3 | 2 |
| 0 | 0 | 3 | 3 |
+----------+----------+-----------------+-----------------+
【讨论】:
@ambako 似乎您在 Martin 的回答中找到了价值。也许你应该对他的时间和才华表示感谢并接受答案以上是关于SQL Server openjson的主要内容,如果未能解决你的问题,请参考以下文章
ms sql2012 能否安装在win2008 server
Sql server2008! SQL server服务无法启动,并显示错误17113, 修复Sql server2008失败!
已安装 SQL Server 2005,安装 SQL Server 2008 时提示需要删除 SQL Server 2005 Express 工具