SQL CROSS TAB&枢

时间:2012-09-12 03:00:24

标签: sql sql-server pivot crosstab

我使用以下查询来检索一些结果

SELECT  CONVERT(varchar, TS.StaffID) + CHAR(13) 
        + SUBSTRING ( TS.GivenName, 1 , 1 ) + '.' + CHAR(13) 
        + TS.Surname AS EmployeeInfo, SH.Hours,ts.UnitID,sh.RowID
         FROM dbo.tbl_TimesheetStaff AS TS
         Left OUTER JOIN
         dbo.tbl_StaffHours AS SH ON
         SH.ActivityUnitID = TS.ActivityUnitID
         AND Sh.StaffID=ts.StaffID
         WHERE TS.UnitID=1

结果集看起来像

   EmployeeInfo   Hours  UnitID RowID
    114 H. Bar     73.71    111   401
    114 H. Bar     42.44    111   402
    115 M. Cha     20.39    111   401
    115 M. Cha     3.616    111   402
    116 Q. Xyz     20.39    111   401
    116 Q. Xyz     3.61     111   402

现在我想要的是将EmployeeInfo列值转换为列名

   114 H. Bar  115 M. Cha  116 Q. Xyz  RowID
     73.71       20.39       20.39      401
     42.44       3.616       3.61       402

EmployeeInfo中的行数可能有所不同,因此我需要一个动态的透视功能。

任何线索......?

1 个答案:

答案 0 :(得分:2)

试试这个:

create table #t table(EmployeeInfo varchar(20),  Hours float, UnitID int, RowID int)
insert into #t
SELECT  CONVERT(varchar, TS.StaffID) + CHAR(13)  
        + SUBSTRING ( TS.GivenName, 1 , 1 ) + '.' + CHAR(13)  
        + TS.Surname AS EmployeeInfo, SH.Hours,ts.UnitID,sh.RowID 
         FROM dbo.tbl_TimesheetStaff AS TS 
         Left OUTER JOIN 
         dbo.tbl_StaffHours AS SH ON 
         SH.ActivityUnitID = TS.ActivityUnitID 
         AND Sh.StaffID=ts.StaffID 
         WHERE TS.UnitID=1 



DECLARE @cols AS NVARCHAR(MAX), 
    @query  AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(EmployeeInfo)  
                    from #t 
            FOR XML PATH(''), TYPE 
            ).value('.', 'NVARCHAR(MAX)')  
        ,1,1,'') 

set @query = 'SELECT RowID,  ' + @cols + '   
                from #t 
            pivot  
            ( 
                MAX([Hours]) 
                for Code in (' + @cols + ') 
            ) p ' 
print(@query) 
execute(@query)