如何使用数据透视表显示动态列

时间:2013-08-03 07:55:14

标签: sql-server

我有一个查询

declare @Leavetype varchar (Max)    
select @Leavetype =(select LeaveName from LeaveType)     

SELECT *
 FROM 
 ( SELECT e.EmpID,
 e.EmpName , 
 s.LeaveName, 
 case when l.Approval = 'Approved'
 then l.TotalDays 
 else
 0
 end  AS Total
  from  EmpInfo e
  full JOIN  ViewLeave l   ON e.EmpID = l.EmpID
  LEFT  JOIN LeaveType  s  ON s.LeaveID = l.LeaveID    

 Where
      l.year = '2013'              

 GROUP BY s.LeaveName,e.EmpID, e.EmpName ,l.Approval,l.TotalDays
 )ps
 pivot
 (
 sum(Total)
 for LeaveName In ([@LeaveType])

 )as pvt         

我想从离开类型表Leavetype

中获取动态值

LeaveType表格如下

ID   Leave type
1    SickLeave
2    Casual Leave

LeaveType表值可能会有所不同,我必须显示

等数据
EmpId    EmpName    SickLeave     Casual Leave 

101      ramesh       1               0

列的数量取决于Leavetype

中的行数

如果有人有想法,请帮帮我

此当前查询显示错误

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

由于

1 个答案:

答案 0 :(得分:0)

您接近这个想法但是必须使用动态sql来动态地转动表。您遇到的错误是因为select @Leavetype =(select LeaveName from LeaveType),即子查询只能返回一个值,以便为变量赋值。

您需要做的是大致如下所示,其中使用逗号分隔的值(列)字符串来构建数据透视查询。

-- get a comma delimited string of the columns
DECLARE @leaveType NVARCHAR(1000)
SELECT @leaveType = STUFF(
                      (SELECT DISTINCT TOP 100 PERCENT '],[' + LeaveName
                       FROM LeaveType AS t
                       FOR XML PATH('') 
                      ), 1, 2, ''
                    ) + ']'

-- create the sql script to be executed
DECLARE @sql NVARCHAR(3000) = N'
    WITH data AS
    (
        SELECT 
            e.EmpID,
            e.EmpName , 
            s.LeaveName, 
            Total = CASE l.Approval 
                        WHEN ''Approved'' THEN l.TotalDays 
                        ELSE 0 
                    END
        FROM EmpInfo e
        FULL JOIN ViewLeave l ON e.EmpID = l.EmpID
        LEFT JOIN LeaveType s ON s.LeaveID = l.LeaveID
        GROUP BY s.LeaveName, e.EmpID, e.EmpName, l.Approval, l.TotalDays
    )

    SELECT *
    FROM data
    PIVOT
    (
        SUM(Total)
        FOR LeaveName IN (' + @leaveType + ')
    ) piv
' 

PRINT @sql
EXEC sp_executesql @sql

Here是一篇博文,详细讨论了PIVOT