Microsoft SQL Server Certification Course
- 5k Enrolled Learners
- Weekend
- Live Class
Relational databases store humongous amounts of data in the form of tables. These tables can have any number of rows and columns. But, what if you had to change the row-level data to columnar data? Well, in this article on SQL Pivot, I will show you how you can convert rows to a column in a SQL Server.
The following topics will be covered in this article:
PIVOT is used to rotate the table-value by converting the unique values of a single column to multiple columns. It is used to rotate the rows to column values and run aggregations when required on the remaining column values.
UNPIVOT, on the other hand, is used to carry out the opposite operations. So, it is used to convert the columns of a specific table to column values.
Moving on in this article, let us understand the syntax of SQL Pivot. You can even check out the details of relational databases, functions, queries, variables, etc with the SQL Server Certification.
SELECT NonPivoted ColumnName, [First Pivoted ColumnName] AS ColumnName, [Second Pivoted ColumnName] AS ColumnName, [Third Pivoted ColumnName] AS ColumnName, ... [Last Pivoted ColumnName] AS ColumnName FROM (SELECT query which produces the data) AS [alias for the initial query] PIVOT ( [AggregationFunction](ColumName) FOR [ColumnName of the column whose values will become column headers] IN ( [First Pivoted ColumnName], [Second Pivoted ColumnName], [Third Pivoted ColumnName] ... [last pivoted column]) ) AS [alias for the Pivot Table];
Here, you can also use the ORDER BY clause to sort the values either in the ascending or descending order. Now that you know what is PIVOT in SQL and its basic syntax, let us move forward and see how to use it.
For your better understanding, I will be considering the following table to explain you all the examples.
SupplierID | DaysofManufacture | Cost | CustomerID | PurchaseID |
1 | 12 | 1230 | 11 | P1 |
2 | 21 | 1543 | 22 | P2 |
3 | 32 | 2345 | 11 | P3 |
4 | 14 | 8765 | 22 | P1 |
5 | 42 | 3452 | 33 | P3 |
6 | 31 | 5431 | 33 | P1 |
7 | 41 | 2342 | 11 | P2 |
8 | 54 | 3654 | 22 | P2 |
9 | 33 | 1234 | 11 | P3 |
10 | 56 | 6832 | 33 | P2 |
Let us write a simple query to retrieve the average cost spent by each customer.
SELECT CustomerID, AVG(Cost) AS AverageCostofCustomer FROM Suppliers GROUP BY CustomerID;
CustomerID | AverageCostofCustomer |
11 | 1787.75 |
22 | 4654 |
33 | 5238.33 |
Now, let us say we want to pivot the above table. Here, the CustomerID column values will become the column headers.
-- Create Pivot table with one row and three columns SELECT 'AverageCostofCustomer' AS Cost_According_To_Customers, [11], [22], [33] FROM (SELECT CustomerID, Cost FROM Suppliers) AS SourceTable PIVOT ( AVG(Cost) FOR CustomerID IN ([11], [22], [33]) ) AS PivotTable;
Cost_According_To_Customers | 11 | 22 | 33 |
AverageCostofCustomer | 1787.75 | 4654 | 5238.33 |
Note: When you use aggregate functions with PIVOT, null values are not considered while computing an aggregation.
Well, that was a basic example, but let us now understand how the PIVOT clause worked.
You can refer above, to create a PIVOT TABLE, you need to follow the steps below:
Initially, we have to specify the fields to be included in our results. In our example, I considered the AverageCostofCustomer column in the Pivot table. Then we created three other columns with the column headers 11, 22, and 33. Example-
SELECT 'AverageCostofCustomer' AS Cost_According_To_Customers, [11], [22], [33]
Next, you have to specify the SELECT statement which will return the source data for the pivot table. In our example, we are returning the CustomerID and Cost from the Suppliers table.
(SELECT CustomerID, Cost FROM Suppliers) AS SourceTable
Next, you have to specify the aggregate function to be used while creating the pivot table. In our example, I have used the AVG function to calculate the average cost.
PIVOT ( AVG(Cost)
Finally, you have to mention the values which have to be included in the resultant pivot table. These values will be used as the column headings in the pivot table.
FOR CustomerID IN ([11], [22], [33]) ) AS PivotTable;
That’s how the PIVOT operators work. Moving on in this article on SQL PIVOT, let us understand how different it is from SQL UNPIVOT.
The SQL UNPIVOT operator is used to carry out the opposite operation to that of PIVOT. It is used to rotate the column data into row-level data. The syntax, of UNPIVOT, is similar to that of PIVOT. The only difference is that you have to use the SQL Keyword “UNPIVOT”.
Let us create a table with the columns SupplierID, AAA, BBB, and CCC. Also, insert few values.
CREATE TABLE sampletable (SupplierID int, AAA int, BBB int, CCC int); GO INSERT INTO sampletable VALUES (1,3,5,6); INSERT INTO sampletable VALUES (2,9,2,8); INSERT INTO sampletable VALUES (3,8,1,7); GO
SupplierID | AAA | BBB | CCC |
1 | 3 | 5 | 6 |
2 | 9 | 2 | 8 |
3 | 8 | 1 | 7 |
Now, let us say, we want to unpivot the table. To to do that, you can refer to the following code:
SELECT SupplierID, Customers, Products FROM (SELECT SupplierD, AAA, BBB, CCC FROM sampletable) p UNPIVOT (Products FOR Customers IN (AAA, BBB, CCC) )AS example; GO
SupplierID | Customers | Products |
1 | AAA | 3 |
1 | BBB | 5 |
1 | CCC | 6 |
2 | AAA | 9 |
2 | BBB | 2 |
2 | CCC | 8 |
3 | AAA | 8 |
3 | BBB | 1 |
3 | CCC | 7 |
That’s how you can use the SQL PIVOT and UNPIVOT. With this, we come to an end to this article. I hope you understood, how to use SQL. If you wish to learn more about MySQL and get to know this open-source relational database, then check out our MySQL DBA Certification Training which comes with instructor-led live training and real-life project experience. This training will help you understand MySQL in-depth and help you achieve mastery over the subject.
Got a question for us? Please mention it in the comments section of this article on SQL Pivot and I will get back to you.
Course Name | Date | Details |
---|---|---|
Microsoft SQL Server Certification Course | Class Starts on 7th December,2024 7th December SAT&SUN (Weekend Batch) | View Details |
edureka.co