使用 FOR JSON AUTO
或 FOR JSON PATH
在以下记录集(代表产品的属性)上:
attribute | value
-----------------
color | red
size | small
将产生:
[{"attribute":"color","value":"red"},{"attribute":"size","value":"small"}]
有什么方法可以产生以下相反的结果:
{"color":"red","size":"small"}
备注 因为每个产品属性都与其他属性不同;所以这个记录集对于每个产品都是不同的。 PIVOTing 不是一个选项,因为它需要动态 sql!似乎我们需要一个函数才能
CROSS
它与产品表生成例如 产品目录 .
最佳答案
我没有使用 SQL Server 2016 的 JSON 函数,而是使用了 string concatenation function string_agg in SQL Server 2017如以下脚本所示
/*create table ProductAttributes (
product int,
attribute varchar(40),
value varchar(40)
)
insert into ProductAttributes select 1, 'color', 'red'
insert into ProductAttributes select 1, 'size', 'small'
insert into ProductAttributes select 2, 'processor', 'intel'
insert into ProductAttributes select 2, 'ram', '16'
insert into ProductAttributes select 2, 'weight', '2'*/
select
product, '{' + STRING_AGG( '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"' ,',') + '}' as attributes
from ProductAttributes
group by product
两个产品条目的输出如下
产品属性
1 {"颜色":"红色","大小":"小"}
2 {"处理器":"intel","ram":"16","weight":"2"}
如果您使用的是 SQL Server 2017 之前的版本,则可以使用 string concatenation using SQL XML Path如下
SELECT
product,
'{' + STUFF(
(
SELECT
',' + '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"'
FROM ProductAttributes a
where a.product = p.product
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)'
), 1, 1, ''
) + '}' As attributes
from ProductAttributes p
group by product
开发人员将得到相同的结果
我已经更新了上面的 SQL 查询并使用了 String_Escape() 函数 @Eilert 的评论
关于sql-server - 将两列转换为键值 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46168258/