SQL-行转列(PIVOT)实例1
--未旋转之前的查询结果 select s.Name ShiftName,h.BusinessEntityID,d.Name as DpartmentName from HumanResources.EmployeeDepartmentHistory h inner join HumanResources.Department d on h.DepartmentID=d.DepartmentID inner join HumanResources.Shift s on s.ShiftID=h.ShiftID WHERE ENDDATE IS NULL AND d.Name IN('Production','Engineering','Marketing') order by ShiftName
![](https://images2015.cnblogs.com/blog/164992/201512/164992-20151223133757202-494802494.png)
--旋转之后的结果 select ShiftName,Production,Engineering,Marketing from (select s.Name ShiftName,h.BusinessEntityID,d.Name as DpartmentName from HumanResources.EmployeeDepartmentHistory h inner join HumanResources.Department d on h.DepartmentID=d.DepartmentID inner join HumanResources.Shift s on s.ShiftID=h.ShiftID WHERE ENDDATE IS NULL AND d.Name IN('Production','Engineering','Marketing') )t pivot (count(BusinessEntityID) for DpartmentName in ([Production],[Engineering],[Marketing]))b order by ShiftName
![](https://images2015.cnblogs.com/blog/164992/201512/164992-20151223133924421-1030395900.png)
不断的总结,才能不断的提高;不断的思考,才能不断的进步!