0

I want to combine records' fields values (to be comma separated) based on another field in the record. To get the issue better, kindly check the example below, I tried to simplify the scenario as much as possible

I've the following table, assume it is called 'My_Table'

+------+-------+
| Key  | Val   |
+------+-------+
| A    | 5     |
| B    | 8     |
| A    | 7     |
| C    | 4     |
| B    | 8     |
| B    | 9     |
| C    | 6     |
+------+-------+

I need a query to retrieve the following table

+-------+--------+
| Key   | Vals   |
+-------+--------+
| A     | 5,7    |
| B     | 8,9    |
| C     | 4,6    |
+-------+--------+

Kindly note that [B, 8] exists twice, I don't want the result to be

+-------+--------+
| Key   | Vals   |
+-------+--------+
| A     | 5,7    |
| B     | 8,8,9  |
| C     | 4,6    |
+-------+--------+

PS, I'm using MySql if it matters.


[UPDATE] BTW, it's not a duplicate question, the extra piece of info is solving the duplication

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82

2 Answers2

1

Group by the first column and use GROUP_CONCAT() to comma seperate the values

select `key`, group_concat(distinct val) as vals
from your_table
group by `key`
juergen d
  • 201,996
  • 37
  • 293
  • 362
0

Try the following query

 SELECT `KEY`, GROUP_CONCAT(Val SEPARATOR ",") as vals
  from table group by `KEY`; 
geoandri
  • 2,360
  • 2
  • 15
  • 28
  • 1
    `key` is a [reserved word](http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html) and needs to be escaped with backticks. – juergen d Oct 16 '14 at 11:00