Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL Grouping with value separations not working

I have a MySQL table that records item with item, make, model & serial number as follows :

item table

item_name make model serial_no qty
Computer HP Pro 300D 123ert34c10 1
Computer HP Pro 400D 123xgt34c110 1
Printer Canon ir1210 56tyu78 1
Computer HP Pro 400D 123xgt34c111 1
Printer Canon ir1215 gh90fr 1
UPS APC A200 apc5640400 1
UPS APC A300 apc5640401 1
Computer HP Pro 300D 123ert34c13 1

Then I need to group items by the item_name and make. And also needs to show all models & serial nos in the group summary as follows :

Desired Output

item_name make model serial_no qty
Computer HP Pro 300D, Pro 400D 123ert34c10, 123ert34c13, 123xgt34c110, 123xgt34c111 4
Printer Canon ir1210, ir1215 56tyu78, gh90fr 2
UPS APC A200, A300 apc5640400, apc5640401 2

I used the following simple query to do this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT item_name, make, model, serial_no, SUM(qty) AS qty FROM item GROUP BY item_name, make 

But the query outs the following output without showing all models & serial nos under the relevant item_name & make.

Incorrect Output

item_name make model serial_no qty
Computer HP Pro 300D 123ert34c10 4
Printer Canon ir1210 56tyu78 2
UPS APC A200 apc5640400 2

Some models & serial nos were missing. What may going wrong. Can anyone help ?

>Solution :

You can achieve the Desired_Output by using GROUP_CONCAT(). Here is the modified sql

SELECT
    item_name,
    make,
    GROUP_CONCAT(DISTINCT model ORDER BY model) AS model,
    GROUP_CONCAT(DISTINCT serial_no ORDER BY serial_no) AS serial_no,
    SUM(qty) AS qty
FROM item
GROUP BY item_name, make;

The DISTINCT ensures model and serial_no are included only once, while GROUP_CONCAT concatenates the results after they are sorted using ORDER BY

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading