I have a table like this,
CREATE TABLE foo (
id integer,
col1 integer,
col2 integer,
col3 integer,
col4 integer,
col5 integer
);
INSERT INTO foo (id, col1, col2, col3, col4, col5)
VALUES
(322, NULL, 3, 1, 2, 2),
(323, 1, 3, 1, 2, 2),
(324, 1, 1, 1, 2, 2),
(325, 3, 3, 3, 3, NULL);
I need to write a query such that I need to get
ID, concatinated string of unique value from the columns without null
My desired output should be
ID, UniqVal
322, "3,1,2"
323, "1,3,2"
324, "1,2"
325, "3"
Note: The version is MySQL 5.5
Best Answer
Select each column along with the ID where the column
IS NOT NULL
. UseUNION
to combine the result sets. This will already eliminate duplicates. ThenGROUP BY
the ID and use thegroup_concat()
aggregation function to build your list.SQL Fiddle