I am going to create temp tables as follows Employee, Department, relationship employee & department i.e. EmpDeptRelation, an employee who conducted the number of lectures in the EmpLectures table.
First, we are going to check these temp tables are already present or not. If present, then drop that tables. Also, after the creation of tables, we need to insert some dummy data into that.
Step 2
As per the above syntax of CTE, we will create some queries & execute that queries.
Firstly will fire only select queries on each table to check the records as,
- Select * from #Employee
- Select * from #Dept
- Select * from #EmpDeptRelation
- Select * from #EmpLectures
Step 3
Now, let's say the user wants to get some data, such as the information of employee id, employee name, department ID & name from above tables. Then, we will use the join clause and as per the above CTE syntax, it will create CTE & will execute it as.
- WITH EmpDetails AS
- (
- Select E.EmpId, E.EmpName, D.DeptId, D.DeptName
- From #Employee E
- INNER JOIN #EmpDeptRelation EDR ON EDR.EmpId = E.EmpId
- INNER JOIN #Dept D on D.DeptId = EDR.DeptId
- )
- Select * from EmpDetails
Now, run the above query. You will get the output as below.
Step 4
Suppose, the user would like to get all lectures conducted by the employee and result set will be like Employee ID, employee name, department ID, department name, lecture date etc. Then in this case we will use above CTE from step 2 and apply into outer CTE and employee lecture table so will compare employee ID to select records.
- ;WITH EmpDetails AS
- (
- Select E.EmpId, E.EmpName, D.DeptId, D.DeptName
- From #Employee E
- INNER JOIN #EmpDeptRelation EDR ON EDR.EmpId = E.EmpId
- INNER JOIN #Dept D on D.DeptId = EDR.DeptId
- )
- SELECT ED.EmpId,
- ED.EmpName,
- ED.DeptId,
- ED.DeptName,
- EL.LectDt
- FROM #EmpLectures EL
- OUTER APPLY
- (
- SELECT TOP 1 * FROM EmpDetails Where EmpDetails.EmpId = EL.EmpId
- ) AS ED
Here, in the above query, I have created CTE name EmpDetails & this will be used further to get records/columns as EmpId,EmpName,DeptId, DeptName.
Now, run the above query and will get output as,
Note
Here is no necessity to select all columns names in the select query those who are used in CTE as in below query I have commented the DeptId, DeptName.
- ;WITH EmpDetails AS
- (
- Select E.EmpId, E.EmpName, D.DeptId, D.DeptName
- From #Employee E
- INNER JOIN #EmpDeptRelation EDR ON EDR.EmpId = E.EmpId
- INNER JOIN #Dept D on D.DeptId = EDR.DeptId
- )
- SELECT ED.EmpId,
- ED.EmpName,
-
-
- EL.LectDt
- FROM #EmpLectures EL
- OUTER APPLY
- (
- SELECT TOP 1 * FROM EmpDetails Where EmpDetails.EmpId = EL.EmpId
- ) AS ED
Now, run the above query. Will get the output as -
Step 5
Suppose user would like to know the total number of lecture counts then will use below query,
- Select E.EmpId,COUNT(E.DeptId) as [TotalLectures] from #EmpLectures E Group by E.EmpId