PIVOT&UNPIVOT

如果是家电销售员,那么可能需要统计每月日销售的彩电、冰箱、空调...最大值、最小值、平均值等

如果你是耳鼻喉科医生,那么可能需要统计月度年度日接客咽炎、喉炎、鼻炎...最大值、最小值、平均值等

如果你是程序媛,那么可能需要统计月度日处理bug、新增功能、支援...等类别问题量的最大值、最小值、平均值等

那么诸如此类问题,需要一行显示一人负责所有相关类别数值时,就是pivot派上用场之时

这类数据结构一般为

create table objecttable(id int primary key identity(1,1),userno varchar(10),calendar date,type varchar(20),num int)

目标输出数据结构

userno type num calendar

---------- ---------- -----------

userA 类别1 1      date1

userB 类别2 3  date2

userC 类别3 5  date3

select userno,max(num) maxnum,type,convert(varchar(7),calendar,120) monthly

into #

from objecttable group by userno,convert(varchar(7),calendar,120),type

select  * from # pivot(max(maxnum) for type in(类别1,类别2,类别3)) x

userno   monthly   类别1   类别2   类别3

-----------------------------------------------------------
userA    2016-06   10     11      15
userB    2016-06   6       3     8
userC    2016-06   9       2     7

附PIVOT语法

SELECT * FROM TB PIVOT(聚合函数(列) FOR 列 in (…) ) tt

UNPIVOT相反操作

select  * into #rlst from # pivot(max(maxnum) for type in(类别1,类别2,类别3)) x


select userno,monthly,type,num from #rlst unpivot(num for type in([类别1],[类别2],[类别3]))xx

完整语法:

select f1,f2,typename,num fom tb

UNPIVOT(

value_column

FOR pivot_column

IN(<column_list>)

)

原文地址:https://www.cnblogs.com/jeffry/p/5629340.html