CREATE TABLE t(Id int, typee nvarchar(50), jsonStr nvarchar(max));
INSERT INTO t(Id, typee, jsonStr) VALUES
(3786, 'APV', '{"1":1,"3":3,"4":24,"5":95}'),
(3786, 'VN', '{"1":3,"5":25}');
-- Expected result
-- {"APV": {"1":1,"3":3,"4":24,"5":95}, "VN":{"1":3,"5":25} }
SELECT Id,(
SELECT CASE WHEN typee = 'VN' THEN jsonStr END AS [VN]
, CASE WHEN typee = 'VO' THEN jsonStr END AS [VO]
, CASE WHEN typee = 'APV' THEN jsonStr END AS [APV]
FROM t AS x
WHERE x.Id = t.Id
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER
) AS TEST1
FROM t
GROUP BY Id
我想得到如下输出:
{
"APV": {
"1": 1,
"3": 3,
"4": 24,
"5": 95
},
"VN": {
"1": 3,
"5": 25
}
}