I have been searching for hours without a decent answer.
I want to transform this table:
Client_id Date
----------- ------------
1 2013-02-03
1 2013-02-10
1 2013-05-12
2 2013-02-03
2 2013-07-15
To:
Client_id Date1 Date2 Date3 Date4, Date5, Date6...
----------- ------------ ------------ ------------ ------------
1 2013-02-03 2013-02-10 2013-05-12
2 2013-02-03 2013-07-15
In order to get this result, you will want to pivot the data. MySQL does not have a pivot function but you can use an aggregate function with a
CASE
expression.If the number of dates is known, then you can hard-code the query:
See SQL Fiddle with Demo
I implemented user variables to assign a row number to each record within the
client_id
group.If you have an unknown number of dates, then you will need to use a prepared statement to create the sql dynamically:
See SQL Fiddle with Demo.
They both give the result: