[英]Parse nested JSON in SQL Server
我已经将数据以Json格式存储在sql服务器中,如下所示。 我想将其检索为普通的字符串值。 我尝试了JSON_VALUE,但是json可能有一个或多个孩子,所以它应该检索所有值。
输入项
表A
ID Education
-------------------------------------------------------------------------------------
1 {"Education": {"Record":[{"SLSubject":"MICRO ECONOMICS","Score":"77","Grade":"A"}]}}
2 {"Education": {"Record":[{"SLSubject":"Math","Score":"89","Grade":"A"},{"SLSubject":"eng","Score":"88","Grade":"B"},{"SLSubject":"tam","Score":"33","Grade":"C"}]}}
3 {"Education":{"Record":[{"SLSubject":"subject 1","Score":"87","Grade":"A"},{"SLSubject":"subject 2","Score":"67","Grade":"B"},{"SLSubject":"subject 3","Score":"45","Grade":"C"},{"SLSubject":"subject 4","Score":"87","Grade":"D"}]}}
预期产量
ID Education
-------------------------------------------------------------------------------------
1 MICRO ECONOMICS - 77 - A
2 Math - 88 - B \n end - 88 - B \n Tam - 33 - C
3 subject 1 - 87- A \n subject 2 - 67- B \n subject 3 - 45- C \n subject 1 - 87- D \n
查询 (适用于一个孩子)
SELECT ID, JSON_VALUE(Education,'$.Education.Record[0].SLSubject')
FROM TableA
实际结果
ID Education
-------------------------------------------------------------------------------------
1 MICRO ECONOMICS - 77 - A
2 Math - 88 - B
3 subject 1 - 87- A
样本JSON:
{"Education":{"Record":[{"SLSubject":"subject 1","Score":"87","Grade":"A"},{"SLSubject":"subject 2","Score":"67","Grade":"B"},{"SLSubject":"subject 3","Score":"45","Grade":"C"},{"SLSubject":"subject 4","Score":"87","Grade":"D"}]}}
您需要使用OPENJSON
并将数据视为数据集, JSON_VALUE
用于返回标量值。 这可能是您真正想要的:
SELECT YT.ID,
OJ.SLSubject,
OJ.Score,
OJ.Grade
FROM (VALUES(1,N'[{"SLSubject":"MICRO ECONOMICS","Score":"77","Grade":"A"}]'),
(2,N'[{"SLSubject":"Math","Score":"89","Grade":"A"},{"SLSubject":"eng","Score":"88","Grade":"B"},{"SLSubject":"tam","Score":"33","Grade":"C"}]'),
(3,N'[{"SLSubject":"subject 1","Score":"87","Grade":"A"},{"SLSubject":"subject 2","Score":"67","Grade":"B"},{"SLSubject":"subject 3","Score":"45","Grade":"C"},{"SLSubject":"subject 4","Score":"87","Grade":"D"}]'))YT(ID,Education)
CROSS APPLY OPENJSON(YT.Education)
WITH (SLSubject varchar(20),
Score int,
Grade char(1)) OJ;
好像OP想要这个吗?
SELECT YT.ID,
STRING_AGG(CONCAT(OJ.SLSubject, ' - ', OJ.Score, ' - ', OJ.Grade),' \n ') WITHIN GROUP (ORDER BY OJ.SLSubject) AS Education
FROM (VALUES(1,N'[{"SLSubject":"MICRO ECONOMICS","Score":"77","Grade":"A"}]'),
(2,N'[{"SLSubject":"Math","Score":"89","Grade":"A"},{"SLSubject":"eng","Score":"88","Grade":"B"},{"SLSubject":"tam","Score":"33","Grade":"C"}]'),
(3,N'[{"SLSubject":"subject 1","Score":"87","Grade":"A"},{"SLSubject":"subject 2","Score":"67","Grade":"B"},{"SLSubject":"subject 3","Score":"45","Grade":"C"},{"SLSubject":"subject 4","Score":"87","Grade":"D"}]'))YT(ID,Education)
CROSS APPLY OPENJSON(YT.Education)
WITH (SLSubject varchar(20),
Score int,
Grade char(1)) OJ
GROUP BY YT.ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.