Сводная таблица со случаем, когда ошибка условия.
Когда я выполняю хранимую процедуру, она генерирует ошибку, о которой говорится ниже..
Msg 207, Level 16, State 1, Line 7 Invalid column name 'CL'. Msg 207, Level 16, State 1, Line 13 Invalid column name 'H'. Msg 207, Level 16, State 1, Line 15 Invalid column name 'A'. Msg 207, Level 16, State 1, Line 15 Invalid column name 'P'.
Что я уже пробовал:
ALTER Procedure [dbo].[Pivot_Attendance2] As Begin SELECT DISTINCT ReportingDate INTO #Dates FROM EmployeesAttendance ORDER BY ReportingDate DECLARE @cols NVARCHAR(4000) SELECT @cols = COALESCE(@cols + ',[' + CONVERT(varchar, DATEPART(DAY, ReportingDate), 112) + ']','[' + CONVERT(varchar,DATEPART(DAY, ReportingDate), 112) + ']') FROM #Dates ORDER BY ReportingDate -- Building the query with dynamic dates --DECLARE @qry NVARCHAR(4000) --SET @qry = --'SELECT * FROM --(SELECT EmpID, Status , ReportingDate --FROM EmployeesAttendance)emp --PIVOT (MAX(Status) FOR ReportingDate IN (' + @cols + ')) AS stat' DECLARE @qry NVARCHAR(4000) = N'SELECT * FROM (SELECT EmpID, ReportingDate, CASE WHEN [Days] IS null AND EXISTS (SELECT 1 FROM EmpApplication WHERE EmployeesAttendance.Empid = EmpApplication.Empid AND (ReportingDate >= LeavFrom AND ReportingDate <= LeavTo)) THEN CL WHEN [Days] IS null AND EXISTS (SELECT 1 FROM Holidays WHERE ReportingDate = HolidayDate) THEN H WHEN [Days] IS null THEN A WHEN [Days] = 1 THEN P END AS Status, DATEPART(DAY, EmployeesAttendance.ReportingDate)as DDate FROM EmployeesAttendance )emp PIVOT (MAX(Status) FOR DDate IN (' + @cols + ')) AS stat ' -- Executing the query EXEC(@qry) END