Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于SQL中JSON集形式的唯一ID合并行_Sql_Json_Sql Server - Fatal编程技术网

基于SQL中JSON集形式的唯一ID合并行

基于SQL中JSON集形式的唯一ID合并行,sql,json,sql-server,Sql,Json,Sql Server,我有一个表,我想根据公共ID合并行 ID file_id quantity 3 1122 25 3 1123 3 4 1126 7 4 1127 1 我想去 ID file_quantity_merged 3 {["file_id":1122, "quantity": 25],["file_id":1123, "quantity": 3]} 4

我有一个表,我想根据公共ID合并行

ID     file_id   quantity

3       1122       25
3       1123        3
4       1126        7
4       1127        1
我想去

ID     file_quantity_merged

3       {["file_id":1122, "quantity": 25],["file_id":1123, "quantity": 3]}
4       {["file_id":1126, "quantity": 7],["file_id":1127, "quantity": 1]}
我没有添加任何试图添加的代码,因为我不确定sql server是否有这样的方法来动态创建json,比如
SET@json
,因为我有一个大文件。
谢谢你的帮助

您想要的结果不是有效的JSON

您需要一个对象数组,而不是花括号中以逗号分隔的数组列表

只要你在一个支持你的版本上,你就可以使用它

SELECT   ID,
         ( SELECT file_id, quantity
           FROM    YourTable T2
           WHERE   T2.ID = T1.ID FOR JSON AUTO ) AS file_quantity_merged
FROM     YourTable T1
GROUP BY ID
返回

+----+----------------------------------------------------------------+
| ID |                      file_quantity_merged                      |
+----+----------------------------------------------------------------+
|  3 | [{"file_id":1122,"quantity":25},{"file_id":1123,"quantity":3}] |
|  4 | [{"file_id":1126,"quantity":7},{"file_id":1127,"quantity":1}]  |
+----+----------------------------------------------------------------+

除了上面的回答,我在不支持json的旧版本中尝试过,我们可以在MySQL中使用group_concat方法来处理这种情况:-

SELECT  ID, GROUP_CONCAT(`file_id`, ':',
    `quantity` SEPARATOR ', ') as file_quantity_merged
    from TABLE_NAME GROUP BY id;

Output:-

ID     file_quantity_merged
3      "1122:25, 1123:3"
4      "1126:7, 1127:1"

那么这是SQL Server还是MySQL???“我没有添加任何尝试的代码,因为我不确定sql server是否有创建json的方法”。您是否阅读了文档???版本:5.7.17谢谢,为sql server的更高版本工作,我正在使用非常旧的版本,这是我面临的困难,因为不支持JSON AUTO的
组\u concat MySql函数?