Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I am Joining two different Tables and I am getting Invalid Object on joining the second table using CTE. Please Let me know whether my way of joining is Correct.

What I have tried:

;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 outer join t2 on t1.DepId = t2.DepId
full outer join t3 on t1.DepId = t3.DepId
Posted
Updated 1-May-17 9:15am
v2
Comments
CHill60 1-May-17 15:10pm    
It is much easier for us to help you if you help us ... what are your table schemas, give us some sample data and give us the full error message...please!

1 solution

You are not selecting DepId in CTE t3

[EDIT] As requested, here is my guess at what the modified query should be. Note that I say "guess" because you have still not given me enough any information in the form of table schemas, sample data or expected results.
SQL
;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  Depid, 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 outer join t2 on t1.DepId = t2.DepId
full outer join t3 on t1.DepId = t3.DepId
 
Share this answer
 
v4
Comments
Member 12605293 1-May-17 22:51pm    
Hi Chill,
Thanks for your Reply Sir,Can your modify my query and send me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900