Pivot Tables in MySQL

  1. Briefly about Pivot tables
  2. Pivoting data by means of tools (dbForge Studio for MySQL)
  3. Pivoting data by means of SQL
  4. Automating data pivoting, creating query dynamically

Briefly about Pivot tables

This article deals with the transformation of table data from rows to columns. Such transformation is called pivoting tables. Often, the result of the pivot is a summary table in which statistical data are presented in the form suitable or required for a report.
Besides, such data transformation can be useful if a database is not normalized and the information is stored therein in a non-optimal form. So, when reorganizing the database and transferring data to new tables or generating a required data representation, data pivot can be helpful, i.e. moving values from rows to resulting columns.
Below is an example of the old table of products – ProductsOld and the new one — ProductsNew. It is through the transformation from rows to columns that such a result can be easily achieved.

Here is a pivot table example.

Pivot Table

Pivoting data by means of tools (dbForge Studio for MySQL)

There are applications that have tools allowing to implement data pivot in a convenient graphical environment. For example, dbForge Studio for MySQL includes Pivot Tables functionality that provides the desired result in just a few steps.

Let’s look at the example with a simplified table of orders – PurchaseOrderHeader.

Assume that we need to make a selection from the table and determine the number of orders made by certain employees from specific suppliers. The list of employees, for which information is needed – 250, 251, 252, 253, 254.

A preferred view for the report is as follows.

Report View

The left column VendorID shows the IDs of vendors; columns Emp250, Emp251, Emp252, Emp253, and Emp254 display the number of orders.

To achieve this in dbForge Studio for MySQL, you need to:

  • Add the table as a data source for the ‘Pivot Table’ representation of the document. In Database Explorer, right-click the PurchaseOrderHeader table and select Send to and then Pivot Table in the popup menu.
  • Specify a column the values of which will be rows. Drag the VendorID column to the ‘Drop Rows Fields Here’ box.
  • Specify a column the values of which will be columns. Drag the EmployeeID column to the ‘Drop Column Fields Here’ box. You can also set a filter for the required employees (250, 251, 252, 253, 254).
  • Specify a column, the values of which will be the data. Drag the PurchaseOrderID column to the ‘Drop Data Items Here’ box.
  • In the properties of the PurchaseOrderID column, specify the type of aggregation – Count of values.

We quickly got the result we need.


Pivoting data by means of SQL

Of course, data transformation can be performed by means of a database by writing a SQL query. But there is a slight hitch, MySQL does not have a specific statement allowing to do this.

T-SQL-based example for SQL Server

For example, SqlServer and Oracle have the PIVOT operator that allows making such data transformation. If we worked with SqlServer, our query would look like this.

Example for MySQL

In MySQL, we will have to use the means of SQL. The data should be grouped by the vendor column – VendorID, and for each required employee (EmployeeID), you need to create a separate column with an aggregate function.

In our case, we need to calculate the number of orders, so we will use the aggregate function COUNT.

In the source table, the information on all employees is stored in one column EmployeeID, and we need to calculate the number of orders for a particular employee, so we need to teach our aggregate function to process only certain rows.

The aggregate function does not take into account NULL values, and we use this peculiarity for our purposes.

You can use the conditional operator IF or CASE which will return a specific value for the desired employee, otherwise will simply return NULL; as a result, the COUNT function will count only non-NULL values.

The resulting query is as follows:

Or even like this:

When executed, a familiar result is obtained.


Automating data pivot, creating query dynamically

As can be seen, the query has a certain consistency, i.e. all the transformed columns are formed in a similar manner, and in order to write the query, you need to know the specific values from the table. To form a pivot query, you need to review all the possible values and only then you should write the query. Alternatively, you can pass this task to a server causing it to obtain these values and dynamically perform the routine task.

Let’s return to the first example, in which we formed the new table ProductsNew from the ProductsOld table. There, the values of properties are limited, and we can’t even know all the possible values; we only have the information on where the names of the properties and their value are stored. These are the Property and Value columns, respectively.

The whole algorithm of creating the SQL query comes down to obtaining the values, from which new columns and concatenations of unchangeable parts of the query will be formed.

Variable @PivotQuery will store our query, the text has been formatted for clarity.
After executing it, we will obtain the desired result corresponding to the scheme of the ProductsNew table.
What is more, the query from variable @PivotQuery can be executed in the script using MySQL statement EXECUTE.
Alexey Mikotkin

Alexey Mikotkin

Alexey Mikotkin is a software engineer at Devart. He leads a team that develops SQL Server, MySQL, and Oracle tools. The main development environment is .NET.
Alexey has a great experience in development of client-server applications and GDI/DirectX. New technologies are the point of Alexey's interest.
Alexey Mikotkin

Latest posts by Alexey Mikotkin (see all)