我有一个SQL问题,当我从数据透视表调用I函数时,我收到此错误:
不能在PIVOT运算符中使用,因为它对NULL不是不变的
我找到了以下链接,但我的问题不同,因为我只使用sql server
Cannot be used in the PIVOT operator because it is not invariant to NULLs
我有一个SP,它给出了每天的总工作时间,返回的列是表中的日期记录,当我在日期之下放置一些数据时,SP正常工作:
EMPId 01/08/2015 02/08/2015 03/08/2015 04/08/2015 05/08/2015 06/08/2015 07/08/2015 08/08/2015
000781 4 3 3 2 2 2 2 2
但是当我想改变它来调用计算总工时的函数时,我得到错误。
这是我的代码:
DECLARE @StartDate datetime = '2015-08-01';
DECLARE @EndDate datetime = '2015-08-08';
DECLARE @EmpID nvarchar(6) = '000781';
DECLARE @cols AS VARCHAR(MAX)
DECLARE @query AS VARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME( cast(CONVERT( VARCHAR(20), date,103 ) as varchar(10)))
from
(
select a1.date from (
SELECT DISTINCT date
from PERS_Attendance
where Date between @StartDate AND @EndDate
)a1
) t
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
EXEC(' SELECT EMPId,' + @cols + '
from
(
select EMPId,
date ,
funckey
from
(
select convert(varchar(20), date,103)date, EMPId,funckey
from PERS_Attendance
) src
) x
pivot
(
dbo.GetWorkingHourPerDay(date,EMPId)
for date in (' + @cols + ')
) p where 1=1 ')
我在这一行得到错误:
dbo.GetWorkingHourPerDay(date,EMPId)
如果我将动态查询放入变量然后选择它,我将得到以下结果:
SELECT EMPId,[01/08/2015],[02/08/2015],[03/08/2015],[04/08/2015],[05/08/2015],[06/08/2015],[07/08/2015],[08/08/2015]
from ( select EMPId, date , funckey from
( select convert(varchar(20), date,103)date, EMPId,funckey from PERS_Attendance ) src ) x
pivot ( dbo.GetWorkingHourPerDay(date,EMPId) for date in
([01/08/2015],[02/08/2015],[03/08/2015],[04/08/2015],[05/08/2015],[06/08/2015],[07/08/2015],[08/08/2015]) )
p where 1=1
返回的错误是:
Msg 406,Level 16,State 1,Line 18 dbo.GetWorkingHourPerDay不能在PIVOT运算符中使用,因为它对NULL不是不变的。
Msg 207,Level 16,State 1,Line 1 列名称无效' EMPId'。
我已经选择了empID,为什么我在empID上出错? 如何在日期列
下获得此函数的结果答案 0 :(得分:1)
尝试这样的事情:
SELECT EMPId,[01/08/2015],[02/08/2015],[03/08/2015],[04/08/2015],[05/08/2015],[06/08/2015],[07/08/2015],[08/08/2015]
from ( select EMPId, date , funckey, dbo.GetWorkingHourPerDay(date,EMPId) AS WorkingHours from
( select convert(varchar(20), date,103)date, EMPId,funckey from PERS_Attendance ) src ) x
pivot (MAX(WorkingHours) for date in
([01/08/2015],[02/08/2015],[03/08/2015],[04/08/2015],[05/08/2015],[06/08/2015],[07/08/2015],[08/08/2015]) )
p where 1=1
正如bluefeet所说,在PIVOT子句中你需要一个聚合函数,但你可以在子查询中使用你的UDF。