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

SQL SELECT query to set values with same id on different columns

I currently have a table with two columns: ‘id’ and ‘type’. There can be multiple rows with the same id, but a type cannot be used more than once for each id. Example:

id type
1 type-1
1 type-2
1 type-3
2 type-1
2 type-2

I would like to construct a SELECT query which from the table above, would take every id and output a string containing all the types with the same id. Example:

id types
1 type-1,type-2,type-3
2 type-1,type-2

However, I do not know how I can do this. Can someone help, please?

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

>Solution :

Use GROUP_CONCAT with an appropriate ORDER BY clause:

SELECT id,
      GROUP_CONCAT(type ORDER BY CAST(SUBSTRING_INDEX(type, '-', -1) AS UNSIGNED)) AS types
FROM yourTable
GROUP BY id
ORDER BY id;
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