-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathderivedTable_CTE.sql
64 lines (54 loc) · 1.49 KB
/
derivedTable_CTE.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
--Temporary Table
Select tblDepartment.Name as Department, COUNT(*) as TotalStudents
into #TempStudentCount
from tblStudents
join tblDepartment
on tblDepartment.Id = tblStudents.DepartmentId
group by tblDepartment.Name
Select Department, TotalStudents
From #TempStudentCount
where TotalStudents >= 2
Drop Table #TempStudentCount
--Table variable
Declare @tblStudentCount table
(DeptName nvarchar(50),DepartmentId int, TotalStudent int)
Insert @tblStudentCount
Select d.Name DeptName, s.DepartmentId, COUNT(*) as TotalStudent
from tblStudents s
join tblDepartment d
on d.Id = s.DepartmentId
group by d.Name, DepartmentId
Select DeptName, TotalStudent
From @tblStudentCount
where TotalStudent >= 2
--Derived Table
Select DepartmentName, TotalStudents
from
(
Select d.Name DepartmentName, s.DepartmentId, COUNT(*) as TotalStudents
from tblStudents s
join tblDepartment d
on d.Id = s.DepartmentId
group by d.Name, s.DepartmentId
)
as EmployeeCount
where TotalStudents >= 2
--CTE (Common Table Expression)
With StudentCountByDept(DepartmentName, DepartmentId, TotalStudents)
as
(
Select d.Name DepartmentName, s.DepartmentId, COUNT(*) as TotalStudents
from tblStudents s
join tblDepartment d
on d.Id = s.DepartmentId
group by d.Name, s.DepartmentId
),
WITH StudentCountByGender(GenderId, TotalStudents)
AS (
SELECT s.GenderId, COUNT(*) TotalStudents
FROM tblStudents s
GROUP BY s.GenderId
)
Select GenderId, g.Name Gender, TotalStudents
from StudentCountByGender s
JOIN tblGender g ON g.Id=s.GenderId