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:
select AID, ASID,
M1 as M1_Date, M2 as M2_Date,
M3 as M3_Date, M4 as M4_Date, M5 as M5_Date
from
(
select AID, ASID, Milestone,
MilestoneDate
from yourtable
where AID = whatever -- other filters here
) src
pivot
(
max(milestonedate)
for milestone in (M1, M2, M3, M4, M5...)
) piv
Or you can use an aggregate function with a CASE
statement:
select aid,
asid,
max(case when milestone = 'M1' then milestonedate else null end) M1_Date,
max(case when milestone = 'M2' then milestonedate else null end) M2_Date,
max(case when milestone = 'M3' then milestonedate else null end) M3_Date,
max(case when milestone = 'M4' then milestonedate else null end) M4_Date
from yourtable
where AID = whatever -- other filters here
group by aid, asid
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:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colNames AS NVARCHAR(MAX),
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Milestone)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colNames = STUFF((SELECT distinct ',' + QUOTENAME(Milestone+'_Date')
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT AID, ASID,' + @colNames + ' from
(
select AID, ASID, Milestone,
MilestoneDate
from yourtable
where AID = whatever -- other filters here
) x
pivot
(
max(MilestoneDate)
for Milestone in (' + @cols + ')
) p '
execute(@query)
This is a fairly generic approach:
select
aid, asid,
max (case when milestone = 'M1' then milestonedate else null end) M1Date,
max (case when milestone = 'M2' then milestonedate else null end) M2Date,
max (case when milestone = 'M3' then milestonedate else null end) M3Date,
max (case when milestone = 'M5' then milestonedate else null end) M5Date
from
mytable
group by aid, asid