SQL 行转列

1. 利用 case when then

1 select DeptId,d.DepName, sum(case [Type] when 0 then CountVisit end) as 'NewsType',
sum (case [Type] when 1 then CountVisit end) as 'QuestionType',
sum (case [Type] when 2 then CountVisit end) as 'PolicyType',
sum (case [Type] when 3 then CountVisit end) as 'HomePage',
sum (case [Type] when 4 then CountVisit end) as 'LoginCookie',
sum (case [Type] when 5 then CountVisit end) as 'ShareType',
sum (case [Type] when 6 then CountVisit end) as 'GalleryType' from
(select COUNT(Id) as CountVisit,DeptId,[Type] from VisitLog where AddTime between '" + startDate + "' and '" + endDate + "'
group by DeptId,[Type])a join Department d on DeptId=d.Id group by DeptId,d.DepName

得到的结果是:

2.

原文地址:https://www.cnblogs.com/sunShineJing/p/5177279.html