繁体   English   中英

使用 SQL 分组和连接 Json 行

[英]Group by and Concatenate Json rows with SQL

我有一个包含多行/记录的表,其中包含不同的 json 值。 我想将它们分组并将它们连接到最后一行,作为选择查询的一部分

Id   Col
1    {'a': 1}        
1    {'b': 2} 
2    {'c': 3} 
2    {'d': 4} 
2    {'e': 5}

期望输出

Id   Col
1    {'a': 1, 'b': 2}        
2    {'c': 3, 'd': 4, 'e': 5}

如果您使用的是sql-server ,请尝试以下操作:

CREATE table #temp( Id int,  Col varchar(100))
Insert into #temp values
(1,'{''a'': 1}')      
,(1,'{''b'': 2}')
,(2,'{''c'': 3}')
,(2,'{''d'': 4}')
,(2,'{''e'': 5}')

SELECT DISTINCT id,
          '{' 
         + STUFF((
                  SELECT ',' + Replace(Replace(col,'{',''),'}','')
                  FROM #temp as t1
                  WHERE t1.id = t2.id
                  FOR XML PATH('')
                  ), 1, 1, '')  
         +'}' AS col 
FROM #temp as t2

drop table #temp
SELECT id, CONCAT('{',STRING_AGG(REPLACE(REPLACE(Col,'{',''),'}',''),','),'}') AS COL
FROM table
GROUP BY id

db<>fiddle 中的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM