码迷,mamicode.com
首页 > 数据库 > 详细

SQL-行转列(PIVOT)

时间:2015-12-23 14:13:59      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

--未旋转之前的查询结果
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


技术分享

--旋转之后的结果

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

技术分享


 技术分享

SQL-行转列(PIVOT)

标签:

原文地址:http://www.cnblogs.com/nzyjlr/p/5069711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!