Search code examples
mysqlsqldatabaseduplicates

Select duplicated values from one column and get there value in one row


I have a table with 2 columns like this:

+----------+----------+
| Column A | Column B |
+----------+----------+
|      123 |    ABC   |
|      123 |    XYC   |
|      123 |    FGH   |
|      145 |    QWE   |
|      147 |    YUI   |
+----------+----------+

I want to select all values from table but view it - like this:

+----------+---------+---------+----------+
| Column A | value 1 | value 2 | value 3  |
+----------+---------+---------+----------+
|      123 | ABC     | XYC     | FGH      |
|      145 | QWE     |         |          |
|      147 | YUI     |         |          |
+----------+---------+---------+----------+

Solution

  • If you're not trying to create extra columns in your output, you can simply use GROUP_CONCAT with the separator of your choice. For example:

    SELECT `Column A`, 
           GROUP_CONCAT(`Column B` SEPARATOR ' | ') AS `Values`
    FROM table1
    GROUP BY `Column A`
    

    Output:

    Column A    Values
    123         ABC | XYC | FGH
    145         QWE
    147         YUI
    

    Demo on dbfiddle