Reputation: 7416
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.
Upvotes: 1
Views: 695
Reputation: 7416
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"
Upvotes: 1
Reputation: 453057
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}] |
+----+----------------------------------------------------------------+
Upvotes: 2