在我的查询中,我使用OUTER APPLY
来获取员工在不同情况下的计数,例如
预期输出(From:2017-01-10 to 2017-01-12
)
CDATE TOTAL_COUNT JOIN_COUNT RESIGNED _COUNT ...
2017-01-10 1204 10 2
2017-01-11 1212 5 1
2017-01-12 1216 3 0
以下是我的查询
DECLARE @P_FROM_DATE DATE = '2017-01-01', --From 1st Jan
@P_TO_DATE DATE = '2017-01-10' --to 10th jan
;WITH CTE_DATE
AS
(
SELECT @P_FROM_DATE AS CDATE
UNION ALL
SELECT DATEADD(DAY,1,CDATE)
FROM CTE_DATE
WHERE DATEADD(DAY,1,CDATE) <= @P_TO_DATE
)
SELECT [CDATE]
,[TOTAL_COUNT]
,[JOIN_COUNT]
FROM CTE_DATE
OUTER APPLY (
SELECT COUNT(CASE WHEN [EMP_DOJ] = [CDATE] THEN 1 ELSE NULL END) AS [JOIN_COUNT]
,COUNT(*) AS [TOTAL_COUNT]
,....
,...
FROM [EMPLOYEE_TABLE]
) AS D
但在执行我的查询时,收到以下错误。
消息8124,级别16,状态1,行18多个列在中指定 包含外部引用的聚合表达式。如果 正在聚合的表达式包含一个外部引用,然后是 外部引用必须是表达式中引用的唯一列。
此处列[JOIN_COUNT]
仅产生错误,而此列没有查询正在运行。但我有更多列待处理添加像[JOIN_COUNT]
(例如Resigned_Count,...等)
答案 0 :(得分:1)
您无需outer apply
即可实现此目的,只需将CTE_DATE
valus加入您的员工表,并使用sum(case when <Conditions met> then 1 else 0 end)
group by
CDate
}
select d.CDate
,sum(case when e.Emp_DoJ <= d.CDate
and e.EmployeeResignDate > d.CDate
then 1
else 0
end) as Total_Count
,sum(case when e.Emp_DoJ = d.CDate
then 1
else 0
end) as Join_Count
,sum(case when e.EmployeeResignDate = d.CDate
then 1
else 0
end) as Resign_Count
from CTE_DATE d
left join Employee_Table e
on(d.CDate between e.Emp_DoJ and e.EmployeeResignDate)
group by d.CDate
order by d.CDate