Create PIVOT From SQL Server Table

In this article, I will explain you how to create a pivot from two columns (Sales date and Sales Amount) in sql Table.

Create a table “Monthly_Sales” by using the following Query.

Create table Monthly_Sales(
Sales_Date datetime,
Sales_Amount decimal(18,2)
)

Insert records to the table using the following query.

Insert into Monthly_Sales(Sales_Date, Sales_Amount) values('2014-06-12','2200')
Insert into Monthly_Sales(Sales_Date, Sales_Amount) values('2015-08-23','4000')
Insert into Monthly_Sales(Sales_Date, Sales_Amount) values('2017-09-12','5500')
Insert into Monthly_Sales(Sales_Date, Sales_Amount) values('2018-10-15','1500')
Insert into Monthly_Sales(Sales_Date, Sales_Amount) values('2017-09-12','9000')

Now, the table is ready for pivot. Execute the below query to get the pivot table.

SELECT *
FROM (
    SELECT 
        year(Sales_Date) as [year],left(datename(month,Sales_Date),3)as [month], 
        Sales_Amount as Amount 
    FROM Monthly_Sales
) as s
PIVOT
(
    SUM(Amount)
    FOR [month] IN (jan, feb, mar, apr, 
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pvt

Output for the above mentioned query:

Pivot Result for SQL Query