pivot

CREATETABLE test1([month] varchar(15), val1 int)INSERTINTO test1VALUES('Jan',70),('Feb',12),('Mar',12),('Apr',14);SELECT*FROM(SELECT[month], val1 FROM test1)AS original    PIVOT(        MIN(val1)FOR[month]IN([Jan],[Feb],[Mar],[Apr]))AS PivotTable

Result:

Jan         Feb         Mar         Apr
----------- ----------- ----------- -----------
70          12          12          14


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


Using the Code

Let us have a table name Invoice which has three properties, InvoiceNumber, InvoiceDate, InvoiceAmount. Suppose we have several rows input in the table. Our goal is to display the sum of InvoiceAmount each month.

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

SelectAllQuery.png

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)
)ASpivot

Pivote.png


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章