T-SQL : How to Pivot in the SQL Server table using T-SQL.

In my previouse post i have explained, How to pivot data with PL/SQL. Here i’m using SQL server table and T-SQL to Pivot data.Pivot query helps to compare and compares large amount data and generate more inetract and readble table. So we can rotate rows and columns as per your requirements and it will helps you to generate Multi-Dimentional Reports and dashboards.
image
Step 1 : Create table and insert data using below scripts which contains the data to pivot.

Table Creation Script:
CREATE TABLE Products
( Product_id integer NOT NULL,
  customer_Name varchar(50) NOT NULL,
  order_id integer,
  CONSTRAINT products_pk PRIMARY KEY (Product_id)
);


Insert Statements:
insert into Products values (0001,'Pubudu',10);
insert into Products values (0002,'Pubudu',20);
insert into Products values (0002,'Pubudu',30);
insert into Products values (0003,'Dewagama',30);
insert into Products values (0004,'Dewagama',40);
insert into Products values (0005,'Chamari',10);
insert into Products values (0006,'Chamari',10);
insert into Products values (0007,'Chamari',10);
insert into Products values (0008,'Chamari',10);
insert into Products values (0009,'Chamari',20);
insert into Products values (0010,'Fonseka',20);
insert into Products values (0011,'Fonseka',10);
insert into Products values (0012,'Fonseka',20);

image

Step 2 : When we executing below script, the PIVOT clause would return the following results:
SELECT * FROM
(
  SELECT customer_Name, order_id
  FROM Products
) src
PIVOT
(
  COUNT(order_id)
  FOR order_id IN ([10], [20], [30])
) Piv


You can display Pivoted output as below whenexecuting the above sql code.
image
T-SQL : How to Pivot in the SQL Server table using T-SQL. T-SQL : How to Pivot in the SQL Server table using T-SQL. Reviewed by Pubudu Dewagama on 10:19:00 PM Rating: 5

No comments: