CREATEview vWEmployeeCount AS SELECT DeptName, DepartmentId, COUNT(*) AS TotalEmployees FROM tblEmployee JOIN tblDepartment ON tblEmployee.DepartmentId = tblDepartment.DeptId GROUPBY DeptName, DepartmentId;
SELECT DeptName, TotalEmployees FROM vWEmployeeCount WHERE TotalEmployees >= 2;
Temporary Tables
local temporary tables 只能用於當前 session,也可以在嵌套的 SP 共享; global temporary tables 可用於其他 sessions,且最後一個 connection 關閉時該 table 也會跟著被刪除
EX.
SELECT DeptName, DepartmentId, COUNT(*) AS TotalEmployees INTO#TempEmployeeCount FROM tblEmployee JOIN tblDepartment ON tblEmployee.DepartmentId = tblDepartment.DeptId GROUPBY DeptName, DepartmentId;
SELECT DeptName, TotalEmployees FROM#TempEmployeeCount WHERE TotalEmployees >= 2;
INSERT @tblEmployeeCount SELECT DeptName, DepartmentId, COUNT(*) AS TotalEmployees FROM tblEmployee JOIN tblDepartment ON tblEmployee.DepartmentId = tblDepartment.DeptId GROUPBY DeptName, DepartmentId;
SELECT DeptName, TotalEmployees FROM @tblEmployeeCount WHERE TotalEmployees >= 2;
Derived Tables
derived tables 只能被用於當前的 query
EX.
SELECT DeptName, TotalEmployees FROM ( SELECT DeptName, DepartmentId, COUNT(*) AS TotalEmployees FROM tblEmployee JOIN tblDepartment ON tblEmployee.DepartmentId = tblDepartment.DeptId GROUPBY DeptName, DepartmentId ) -- EmployeeCount 是 derived tables name AS EmployeeCount WHERE TotalEmployees >= 2;