Pivot Table In SQL Query

Example

here is an eg1

	SELECT * FROM (SELECT year(invoiceDate) as [year], left(datename(month,invoicedate),3)as [month], _
	InvoiceAmount as Amount FROM Invoice) as InvoiceResult 

使用 pivot 可以将竖着放的表处理成横着的一行一行

	SELECT *
	FROM (
	    SELECT 
	        year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month], 
	        InvoiceAmount as Amount 
	    FROM Invoice
	) as s
	PIVOT
	(
	    SUM(Amount) --可能对于原来的每个月会有多个数据,因此可以使用聚合函数
	    FOR [month] IN (jan, feb, mar, apr, 
	    may, jun, jul, aug, sep, oct, nov, dec)--只需要写字段的名称即可,不需要加单引号
	)AS pvt

Other Example

  • Before

一个 groupid 对应多个 item,每个 item 对应一个 value(哪个混蛋设计的数据库结构(゜皿゜メ) )

可能需要提取不同 item 对应的 value 因此将其做成透视表来处理

  • After

因为每个 itemcode 只可能有一个数据,因此使用 max 这样的聚合函数也没有问题

最终提取成一行之后就可以对不同的 itemcode 进行比较了

    --pivot table
    SELECT top(20) *
    FROM (
        SELECT datagroupid, itemcode, textanswer
        FROM profile_data
    ) as s
    PIVOT
    (
        max(textanswer)
        FOR itemcode IN (Incident_DateReported,Incident_AssignedTo,Incident_DueDate,Incident_CloseDate,Incident_Status)
    )AS pvt

参考文献

Footnotes

  1. http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query