Mysql – Distinct value across multiple columns

distinctmysql-5.5

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. Use UNION to combine the result sets. This will already eliminate duplicates. Then GROUP BY the ID and use the group_concat() aggregation function to build your list.

SELECT id,
       group_concat(col
                    SEPARATOR ',') uniqval
       FROM (SELECT id,
                    col1 col
                    FROM elbat
                    WHERE col1 IS NOT NULL
             UNION
             SELECT id,
                    col2 col
                    FROM elbat
                    WHERE col2 IS NOT NULL
             UNION
             SELECT id,
                    col3 col
                    FROM elbat
                    WHERE col3 IS NOT NULL
             UNION
             SELECT id,
                    col4 col
                    FROM elbat
                    WHERE col4 IS NOT NULL
             UNION
             SELECT id,
                    col5 col
                    FROM elbat
                    WHERE col5 IS NOT NULL) x
       GROUP BY id;

SQL Fiddle