有什么好的方法,从行列列行的SQL表转数据?(What are some good ways to

2019-08-04 22:14发布

有什么好的方法,从行列列行的SQL表转数据?

还允许过滤器/其中要在初始查询应用的条件。

使用SQL Server 2008。

现有的表有以下栏目:AID(nvarchar的唯一的)ASID(nvarchar的唯一的)里程碑(M1,M2,M3 ... M100)MilestoneDate(日期时间)

换位数据如下:AID,ASID,M1日期,日期M2,M3日期,M5日期

Answer 1:

如果您正在使用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

或者你可以使用一个聚合函数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

上述两个查询工作的伟大,如果你有一个已知数量的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)


Answer 2:

这是一个非常通用的方法:

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


文章来源: What are some good ways to transpose data in a SQL table from row-columns to column-rows?