从Dynamic Pivot处理全局临时表SQL

时间:2016-10-20 08:27:32

标签: sql sql-server sql-server-2008-r2

我有以下查询:

if OBJECT_ID('TempDB..#t1') is not null
    drop table #t1

if OBJECT_ID('TempDB..#t2') is not null
    drop table #t2

if OBJECT_ID('TempDB..##temp') is not null
    drop table ##temp

select            
    a.AssetInspectionID, a.ProjectNo, c.SystemDescription, 
    datepart(year, a.InspectionDate) InspectYear,
    a.InspectionDate, a.AssetID, f.AssetNo, e.SurfaceCondition, 
    a.EquipmentGauging, a.Probe,
    d.CalibrationBlock, a.Couplant,
    b.AssetPartID, g.PartNo, g.PartDescription, 
    b.[0Degree], b.[90Degree], b.[180Degree], b.[270Degree]
into
    #t1
from        
    AIM_AssetInspection a
inner join 
    AIM_AssetInspectionPart b on a.AssetInspectionID = b.AssetInspectionID
inner join 
    AIM_AssetSystem c on a.SystemID = c.SystemID
inner join 
    AIM_AssetCalibrationBlock d on a.CalibrationBlockID = d.CalibrationBlockID
inner join 
    AIM_AssetSurfaceCondition e on a.SurfaceConditionID = e.SurfaceConditionID
inner join 
    AIM_Asset f on a.AssetID = f.AssetID
inner join 
    AIM_AssetPart g on b.AssetPartID = g.AssetPartID
order by    
    a.InspectionDate desc


select            
    a.AssetNo, a.InspectYear, a.InspectionDate, a.ProjectNo, 
    a.SystemDescription, a.SurfaceCondition,
    a.EquipmentGauging, a.Probe, a.CalibrationBlock, a.Couplant,
    a.PartNo, a.PartDescription, 
    a.[0Degree], a.[90Degree], a.[180Degree], a.[270Degree]
into
    #t2
from        
    #t1 a

-- pivot
declare @inspectyear as nvarchar(max), @query as nvarchar(max);

set @inspectyear = STUFF((select distinct ',' + quotename(InspectYear) from #t2 c
                  for XML path(''), type).value('.','NVARCHAR(MAX)'),1,1,'')

set @query =
';with data as
(
      select      assetno, inspectyear,
                  partno, PartDescription, Position, number
      from #t2
      unpivot
      (
            number
            for Position in ([0degree], [90degree], [180degree], [270degree])
      ) unpvt
)
select * into ##temp
from data
pivot
(
      sum(number)
      for inspectyear in (' + @inspectyear + ')
) pvt
order by PartNo'

--execute(@query);
exec sp_executesql @query = @query;

select * from ##temp;
drop table ##temp;

结果应为:

----------------------------------------------------------------------
assetno    partno    partdescription    Position   2009    2011   2013
----------------------------------------------------------------------
EQ001      p1        part #1            0degree    8       8      9
EQ001      p1        part #1            90degree   9       9      8
EQ001      p1        part #1            180degree  7       7      6
EQ001      p1        part #1            270degree  9       9      8
ff.

由于临时表是动态的,我不知道如何进行计算。例如,我想在上面的结果中添加另一列。比方说,Calc列是3列200920112013的计算结果。结果应为25.依此类推其他行。

有没有办法实现这个目标?

真的很感激。

谢谢

0 个答案:

没有答案