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.
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 ?
2
Answers
When you
GROUP BY
you will get a single row for all the data grouped by given column but you will not get any summary or whatever of these data which is what you for some reason expected. This is actually correct forGROUP BY
. If you want get all the details, you would needGROUP_CONCAT()
function instead:You can achieve the
Desired_Output
by usingGROUP_CONCAT()
. Here is the modifiedsql
The
DISTINCT
ensuresmodel
andserial_no
are included only once, whileGROUP_CONCAT
concatenates the results after they are sorted usingORDER BY