有什么方法可以将SQL表中的数据从行列转换为列行?

psa*_*sam 0 sql t-sql transpose pivot sql-server-2008

有什么方法可以将SQL表中的数据从行列转换为列行?

还允许过滤器/在初始查询中应用条件的位置.

使用SQL Server 2008.

现有表具有以下列:AID(nvarchar唯一)ASID(nvarchar唯一)里程碑(M1,M2,M3 ... M100)MilestoneDate(datetime)

转置数据如下:AID,ASID,M1日期,M2日期,M3日期,M5日期

Tar*_*ryn 7

如果您使用的是SQL Server 2005+,则可以使用一些选项来转置数据.您可以实现与PIVOT此类似的功能:

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
Run Code Online (Sandbox Code Playgroud)

或者您可以将聚合函数与CASE语句一起使用:

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
Run Code Online (Sandbox Code Playgroud)

如果您具有已知数量的milestone值,则上述两个查询非常有用.但如果没有,那么你可以实现动态sql来转置数据.动态版本与此类似:

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)
Run Code Online (Sandbox Code Playgroud)