2

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

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 中的行数可以变化,因此我需要一个动态数据透视函数。

任何线索..?

4

1 回答 1

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) 
于 2012-09-12T03:28:10.327 回答