我有 2 个表格,我从中获取报告的数据(我在此示例中使用通用表格):
CREATE TABLE Department
(
DeptId int NOT NULL PRIMARY KEY IDENTITY(1,1),
DepartmentName varchar(20) NOT NULL
)
CREATE TABLE Employee
(
EmpId int NOT NULL PRIMARY KEY IDENTITY(1,1),
FirstName varchar(20) NULL,
LastName varchar(30) NULL,
WorkStatus int NOT NULL,
DeptId int NOT NULL
)
INSERT INTO Department (DepartmentName)
Values ('Finance'),
('Personnel'),
('Research'),
('Info Tech'),
('Production')
INSERT INTO Employee (FirstName, LastName, WorkStatus, DeptId)
VALUES ('Steve', 'Smith', 2, 3),
('Jim', 'Jones', 3, 1),
('Dave', 'Black', 1, 2),
('Nancy', 'White', 2, 4),
('Judith', 'North', 1, 5),
('Austin', 'West', 3, 5),
('Herbert', 'Livingston', 2, 5)
我需要创建一份报告,列出“按部门划分的不同工作状态的数量”,因此 Research 有一个工作状态为 2 的人,依此类推。我通常会使用数据透视查询来处理它,例如:
SELECT DepartmentName, [1] as [Status 1],[2] as [Status 2],[3] as [Status 3] FROM
(SELECT e.EmpId, d.DepartmentName, e.WorkStatus as WkStatus
FROM dbo.Employee e
INNER JOIN dbo.Department d
ON e.DeptId = D.DeptId
WHERE d.DeptId = 1
UNION
SELECT e.EmpId, d.DepartmentName, e.WorkStatus as WkStatus
FROM dbo.Employee e
INNER JOIN dbo.Department d
ON e.DeptId = D.DeptId
WHERE d.DeptId = 2
UNION
SELECT e.EmpId, d.DepartmentName, e.WorkStatus as WkStatus
FROM dbo.Employee e
INNER JOIN dbo.Department d
ON e.DeptId = D.DeptId
WHERE d.DeptId = 3
UNION
SELECT e.EmpId, d.DepartmentName, e.WorkStatus as WkStatus
FROM dbo.Employee e
INNER JOIN dbo.Department d
ON e.DeptId = D.DeptId
WHERE d.DeptId = 4
UNION
SELECT e.EmpId, d.DepartmentName, e.WorkStatus as WkStatus
FROM dbo.Employee e
INNER JOIN dbo.Department d
ON e.DeptId = D.DeptId
WHERE d.DeptId = 5
) UNIONqry
PIVOT
(count(EmpId) for WkStatus in ([1],[2],[3])) pvt
Order by DepartmentName
但是我正在寻找一种更好的方法,因为我正在构建的实际查询有 120 个“部门”,这意味着 120 个工会。我做的最后一个是只有 18 个“部门”,查询需要 2 秒才能运行,所以我假设 120 需要一点时间。所以我想知道是否有更好的方法来解决这个问题,或者我是否应该继续使用上述“联合枢轴”方法。