How can I move a column of dates like below.
User Date
==== ====
001 2012/12/01 09:00
001 2012/12/01 11:00
001 2012/12/01 12:00
001 2012/12/01 13:00
001.. ...
and list them like below.
User date time1 time2 time3 time4 time5
001 2012/12/01 09:00 11:00 12:00 13:00 14:00
Thanks Bluefeet for the solution. I tested the script and got the following result.
2 2012/11/04 09:00:00.000 NULL NULL NULL NULL NULL NULL
2 2012/11/08 NULL 09:00:00.000 18:00:00.000 NULL NULL NULL NULL
2 2012/11/09 NULL NULL NULL 09:00:00.000 18:00:00.000 NULL NULL
2 2012/11/10 NULL NULL NULL NULL NULL 09:00:00.000 18:00:00.000
The time seems to skip to the last null column for the same user at the next date? is there a way for me to arrange them in order starting from the first column for the next date for the same user?
You did not specify what RDBMS you are using but you previously tagged questions with a sql server tag so I will assume that is the database.
You can perform this operation using the
PIVOTfunction in SQL Server. There are two ways that you can do this either static where you hard-code all of the values or dynamic where the values are determined at run-time.Static Pivot:
See SQL Fiddle with Demo
Dynamic Pivot:
See SQL Fiddle with Demo
Aggregate/CASE version:
If for some reason you do not want to use the
PIVOTfunction, then you can also use an aggregate function with aCASEstatement.See SQL Fiddle with Demo
All three produce the same result: