DECLARE @qry NVARCHAR(4000);
SET @qry=N';WITH CTE AS(
SELECT EmpID,
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, ReportingDate)as DDate FROM EmployeesAttendance
)
SELECT * FROM (
SELECT EmpID,Status,Status AS New_status,DDate FROM CTE
) AS Emp
PIVOT (MAX(Status) FOR DDate IN (' + @cols + ')) AS stat
PIVOT(COUNT(New_status) FOR New_status IN ([P],[CL],[A])) AS Pvt;'
EXEC(@qry)