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