CTE中的对象名称无效

时间:2017-05-01 17:42:58

标签: sql sql-server

我已经尝试过CTE在我的下面的查询中结合两个表并获取无效对象错误但它存在。可以任何人指导我吗?

;WITH t1
AS (
    SELECT DepId
        , COUNT(EmpId) AS TotalHeadCount

    FROM Emploee

    WHERE (datepart(yyyy, DOJ) BETWEEN 2005 AND 2017)
        AND STATUS = 0

    GROUP BY DepId
    )
    , t2
AS (
    SELECT DepId
        , COUNT(EmpId) AS NewJoinees

    FROM Emploee

    WHERE (DATEPART(yyyy, DOJ) = 2017)
        AND (DATEPART(mm, DOJ) = 01)
        AND datepart(mm, DOJ) >= 12
        AND STATUS = 0

    GROUP BY DepId
    )
    , t3
AS (
    SELECT Tobehired AS TOBEHIRED
        , OpenPosition AS OPENPOSITION
        , STATUS

    FROM Employee1
    )

SELECT t1.DepId
    , CASE 
        WHEN TotalHeadCount IS NULL
            THEN '0'
        ELSE TotalHeadCount
        END AS TotalHeadCount
    , CASE 
        WHEN NewJoinees IS NULL
            THEN '0'
        ELSE NewJoinees
        END AS NewJoinees
    , Tobehired
    , OpenPosition
    , STATUS

FROM t1

FULL JOIN t2
    ON t1.DepId = t2.DepId

FULL JOIN t3
    ON t1.DepId = t3.DepId

1 个答案:

答案 0 :(得分:0)

使用公用表表达式的时间和地点。我不认为这是其中之一......复杂的连接与嵌套子查询,递归,重构可维护性。在我看来,两桌加入似乎并不合适。

SELECT E.DEPID
     , sum(case when datepart(yyyy,E.doj) between 2005 and 2017 and status =0 then 1 else 0 end as TotalHeadCount
     , sum(case when E.doj >= cast('2017-01-12' as datetime) then 1 else 0 end as NewJoinees
     , E1.Tobehired
     , E1.OpenPosition
     , E1.STATUS
FROM Employee E
LEFT JOIN Emplyee1 E1
 on E.DepID = E1.DepID
GROUP BY E.DEPID,
       , E1.Tobehired
       , E1.OpenPosition
       , E1.STATUS