ifexists (select*from sysobjects where id =object_id('EmployeeType') and type ='u') droptable EmployeeType GO ifexists (select*from sysobjects where id =object_id('Employee') and type ='u') droptable Employee GO ifexists (select*from sysobjects where id =object_id('Department') and type ='u') droptable Department GO createtable Department ( Id intprimarykey, Department varchar(10) ) createtable Employee ( EmployeeId intprimarykey, DepartmentId intForeignKey (DepartmentId) References Department(Id) , --DepartmentId , EmployeeName varchar(10) ) createtable EmployeeType ( EmployeeId intForeignKey (EmployeeId) References Employee(EmployeeId) , --EmployeeId , EmployeeType varchar(10) )
看一下部门、员工和员工类型的列表 Department EmployeeName EmployeeType ---------- ------------ ------------ A Bob 正式 A John 临时 A May 正式 B Tom 正式 B Mark 辞退 B Ken 正式
现在我们需要输出这样一个列表 部门编号 部门名称 合计 正式员工 临时员工 辞退员工
这个问题我的思路是首先统计每个部门的员工类型总数 这个比较简单,我把它做成一个视图
ifexists (select*from sysobjects where id =object_id('VDepartmentEmployeeType') and type ='v') dropview VDepartmentEmployeeType GO createview VDepartmentEmployeeType as select Department.Id, Department.Department, EmployeeType.EmployeeType, count(EmployeeType.EmployeeType) Cnt from Department, Employee, EmployeeType where Department.Id = Employee.DepartmentId and Employee.EmployeeId = EmployeeType.EmployeeId groupby Department.Id, Department.Department, EmployeeType.EmployeeType GO
现在 select * from VDepartmentEmployeeType
Id Department EmployeeType Cnt ----------- ---------- ------------ ----------- 2 B 辞退 1 1 A 临时 1 1 A 正式 2 2 B 正式 2
有了这个结果,我们再通过行列转换,就可以实现要求的输出了 行列转换采用 case 分支语句来实现,如下:
select Id as'部门编号', Department as'部门名称', [正式]=Sum(casewhen EmployeeType ='正式'then Cnt else0end), [临时]=Sum(casewhen EmployeeType ='临时'then Cnt else0end), [辞退]=Sum(casewhen EmployeeType ='辞退'then Cnt else0end), [合计]=Sum(casewhen EmployeeType <>''then Cnt else0end) from VDepartmentEmployeeType GROUPBY Id, Department
DECLARE @sVARCHAR(max) SELECT@s=isnull(@s+',','')+'['+ltrim(EmployeeType)+'] = '+ 'Sum(case when EmployeeType = '''+ EmployeeType +''' then Cnt else 0 end)' FROM (SELECTDISTINCT EmployeeType FROM VDepartmentEmployeeType ) temp EXEC('select Id as 部门编号, Department as 部门名称,'+@s+ ',[合计]= Sum(case when EmployeeType <> '''' then Cnt else 0 end)'+ 'from VDepartmentEmployeeType GROUP BY Id, Department')
SELECT Id as'部门编号', Department as'部门名称', [正式],[临时],[辞退] FROM (SELECT Id,Department,EmployeeType,Cnt FROM VDepartmentEmployeeType) p PIVOT ( SUM (Cnt) FOR EmployeeType IN ([正式],[临时],[辞退]) )AS unpvt