What is SQL Pivoting?
SQL Pivoting means converting rows into columns.
It is mainly used to create summary reports.
Instead of showing data in multiple rows, pivot shows it in a tabular format with columns.
Pivoting Example Table (Sales Data)
Step 1: Create a Table
CREATE TABLE Sales (
Employee VARCHAR(50),
Month VARCHAR(20),
SalesAmount INT
);
Step 2: Insert Data
INSERT INTO Sales VALUES
('John', 'Jan', 100),
('John', 'Feb', 150),
('John', 'Mar', 200),
('Mary', 'Jan', 120),
('Mary', 'Feb', 180),
('Mary', 'Mar', 250);
Step 3: Select Sales Data
SELECT * FROM Sales;
![Select_sales_data]()
Step 4: SQL PIVOT Syntax (SQL Server)
SELECT * FROM
(
SELECT Employee, [Month], SalesAmount FROM Sales
) AS SourceTable
PIVOT
(
SUM(SalesAmount) FOR Month IN ([Jan], [Feb], [Mar])
) AS PivotTable;