简体   繁体   中英

Merge Rows based on unique ID in form of a JSON set in SQL

I have a table and I want to merge rows based on common ID

ID     file_id   quantity

3       1122       25
3       1123        3
4       1126        7
4       1127        1

I want to get

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]}

I haven't added any attempted code as I am not sure if sql server have such method to create json like this SET @json dynamically as I have large file. Any help appreciated.

Your desired result is not valid JSON.

You need an array of objects, not a comma delimited list of arrays in curly brackets.

As long as you are on a version supporting FOR JSON AUTO you can use

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

Which returns

+----+----------------------------------------------------------------+
| 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}]  |
+----+----------------------------------------------------------------+

In addition to above answer, I tried in the older version where json not supported, we may use group_concat method to handle such situations in MySQL:-

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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