What are some good ways to transpose data in a SQL table from row-columns to column-rows?
Also allowing filters/where conditions to be applied on the initial query.
Using SQL Server 2008.
Existing table has following Columns: AID (nvarchar unique) ASID (nvarchar unique) Milestone (M1, M2, M3...M100) MilestoneDate (datetime)
Transposed data as follows: AID, ASID, M1 Date, M2 Date, M3 Date, M5 Date
If you are using SQL Server 2005+, then you have a few options to transpose the data. You can implement the
PIVOT
function similar to this:Or you can use an aggregate function with a
CASE
statement:The above two queries work great if you have a known number of
milestone
values. But if not, then you can implement dynamic sql to transpose the data. The dynamic version would be similar to this:This is a fairly generic approach: