第1章 逻辑查询处理

PIVOT操作涉及以下三个逻辑阶段:
P1: 分组
P2: 扩展
P3: 聚合
斜体样式
Eg:
select empid,[2006],[2007],[2008] from
(select empid,year(orderdate) as orderyear,val from Sales.OrderValues) ov
pivot(sum(val) for orderyear in ([2006],[2007],[2008])) as p

UNPIVOT操作涉及三个逻辑阶段:
U1: 生成副本
U2: 提取元素
U3: 删除带有NULL的行

select empid,[2006],[2007],[2008]
into dbo.EmpYearSales

from
(select empid,year(orderdate) as orderyear,val from Sales.OrderValues) ov
pivot(sum(val) for orderyear in ([2006],[2007],[2008])) as p;

update dbo.EmpYearSales set [2006] =null where empid in (1,2);

select * from dbo.EmpYearSales;

select empid,orderyear,val from dbo.EmpYearSales
unpivot(val for orderyear in ([2006],[2007],[2008])) as U;

drop table dbo.EmpYearSales

OVER子句: OVER子句可以用在Select阶段和Order By阶段
Eg:
select orderid,custid,count() over(partition by custid) as ordercnt
from Sales.Orders
where shipcountry=N’Spain’
order by count(
) over(partition by custid) desc

你可能感兴趣的:(SQLServer)