0

在我的查询中,我OUTER APPLY用于在不同的情况下获取员工人数,例如

  1. 一段时间内每天加入的员工人数
  2. 期间每天离职员工人数
  3. 一段时间内每天离职的员工人数......等

预期输出 ( 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,...等)

4

1 回答 1

1

您不需要 aouter apply来实现这一点,只需将您CTE_DATE的值加入您的员工表并将 asum(case when <Conditions met> then 1 else 0 end)与 a 一起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
于 2017-01-12T12:18:23.647 回答