2

我有一个查询

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 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

谢谢

4

1 回答 1

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

PIVOT是一篇更详细讨论的博客文章

于 2013-08-03T08:16:49.487 回答