透視是一種通過聚合和旋轉把數據行轉換成數據列的技術。當透視數據時,需要確定三個要素:要在行(分組元素)中看到的元素,要在列(擴展元素)上看到的元素,要在數據部分看到的元素(聚合元素)。
SQL Server數據庫中,PIVOT在幫助中這樣描述滴:可以使用 PIVOT 和UNPIVOT 關系運算符將表值表達式更改為另一個表。PIVOT 通過將表達式某一列中的唯一值轉換為輸出中的多個列來旋轉表值表達式,並在必要時對最終輸出中所需的任何其余列值執行聚合。UNPIVOT 與 PIVOT 執行相反的操作,將表值表達式的列轉換為列值。
數據表如下所示:
with C as ( select YEAR(orderdate) as orderyear,MONTH(orderdate) AS ordermonth,val from Sales.OrderValues ) select * from C PIVOT(sum(val) for ordermonth in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) as P
擴展一下,為每一個顧客返回最近的5此訂單的訂單信息
with C as ( select custid,val,ROW_NUMBER() over(partition by custid order by orderdate desc,orderid desc) as rownum from Sales.OrderValues ) select * from C PIVOT(max(val) for rownum in ([1],[2],[3],[4],[5])) as P
如果我們需要把每個客戶的最近的5分訂單ID鏈接一個字符串,可以使用2012中心的concat函數
CONCAT(字串1, 字串2, 字串3, ...): 將字串1、字串2、字串3,等字串連在一起。
with C as ( select custid,CAST(orderid as varchar(11)) as sorderid,ROW_NUMBER() over(partition by custid order by orderdate desc,orderid desc) as rownum from Sales.OrderValues ) select custid,CONCAT([1],','+[2],','+[3],','+[4],','+[5]) as orderids from C PIVOT(max(sorderid) for rownum in ([1],[2],[3],[4],[5])) as P
https://technet.microsoft.com/zh-cn/library/ms177410(v=sql.105).aspx
這是PIVOT相關文檔說明