How can I return pivot table output in MySQL?

Are you looking for a way to transform your MySQL table into a pivot table, where the rows become columns and the values are aggregated based on certain criteria? If so, you're in the right place. In this article, we will explore how to achieve this pivot table output in MySQL, using a combination of SQL techniques and functions.

Understanding the Problem

Let's start by understanding the problem statement. You have a MySQL table with columns like company_name, action, and pagecount. Each row represents a specific action taken by a company and the corresponding pagecount. Here's a sample dataset:


                CREATE TABLE actions (
                    company_name VARCHAR(50),
                    action VARCHAR(50),
                    pagecount INT
                );

                INSERT INTO actions (company_name, action, pagecount)
                VALUES ('Company A', 'PRINT', 3),
                ('Company A', 'PRINT', 2),
                ('Company A', 'PRINT', 3),
                ('Company B', 'EMAIL', NULL),
                ('Company B', 'PRINT', 2),
                ('Company B', 'PRINT', 2),
                ('Company B', 'PRINT', 1),
                ('Company A', 'PRINT', 3);
            

Your goal is to retrieve the output in the following format:


                | company_name | EMAIL | PRINT_1_PAGES | PRINT_2_PAGES | PRINT_3_PAGES |
                |--------------|-------|---------------|---------------|---------------|
                | Company A    |   0   |       0       |       1       |       3       |
                | Company B    |   1   |       1       |       2       |       0       |
            

This output represents the count of each action/pagecount pair for each company_name. For example, Company A has 1 PRINT action with 3 pages, 1 PRINT action with 2 pages, and 1 PRINT action with 3 pages.

Approach to Solve the Problem

To solve this problem, we will use a combination of SQL techniques, including:

  • GROUP BY clause
  • CASE statement
  • SUM and COUNT functions

Let's dive into the step-by-step guide to achieving the desired pivot table output.

Step 1: Understanding the Data

Before we jump into writing the actual query, let's understand the data structure in more detail. We have three columns: company_name, action, and pagecount. The goal is to group the data by company_name and action, and then pivot the pagecount values as separate columns.

Step 2: Grouping the Data

To achieve this, we will start with a basic GROUP BY query to group the data by company_name and action:


                SELECT company_name, action, pagecount
                FROM actions
                GROUP BY company_name, action
                ORDER BY company_name, action;
            

This will give us the following result:


                | company_name | action | pagecount |
                |--------------|--------|-----------|
                | Company A    | PRINT  |     3     |
                | Company A    | PRINT  |     2     |
                | Company B    | EMAIL  |    NULL   |
                | Company B    | PRINT  |     2     |
                | Company B    | PRINT  |     1     |
            

Notice that we have NULL values for the EMAIL action, as there was no pagecount specified.

Step 3: Pivot the Data

Now comes the tricky part - pivoting the data. We need to transform the pagecount values into separate columns for each action/pagecount pair. We can achieve this using a combination of the CASE statement, SUM function, and GROUP BY clause.

First, let's create a temporary table to store the pivot table output:


                CREATE TEMPORARY TABLE pivot AS
                SELECT company_name, 
                    SUM(CASE WHEN action = 'EMAIL' THEN 1 ELSE 0 END) AS EMAIL,
                    SUM(CASE WHEN action = 'PRINT' AND pagecount = 1 THEN 1 ELSE 0 END) AS PRINT_1_PAGES,
                    SUM(CASE WHEN action = 'PRINT' AND pagecount = 2 THEN 1 ELSE 0 END) AS PRINT_2_PAGES,
                    SUM(CASE WHEN action = 'PRINT' AND pagecount = 3 THEN 1 ELSE 0 END) AS PRINT_3_PAGES
                FROM actions
                GROUP BY company_name
                ORDER BY company_name;
            

This query uses the CASE statement to check the action type and pagecount value for each row. If the conditions match, it adds 1 to the respective column, otherwise, it adds 0. Finally, it groups the data by company_name and orders it in ascending order.

Step 4: Fetch the Pivot Table Output

Now that we have stored the pivot table output in a temporary table, we can retrieve the desired result:


                SELECT * FROM pivot;
            

This will give us the following result:


                | company_name | EMAIL | PRINT_1_PAGES | PRINT_2_PAGES | PRINT_3_PAGES |
                |--------------|-------|---------------|---------------|---------------|
                | Company A    |   0   |       0       |       1       |       3       |
                | Company B    |   1   |       1       |       2       |       0       |
            

Conclusion

In this article, we have explored how to solve the problem of returning pivot table output in MySQL. By following the step-by-step guide and using a combination of SQL techniques, we were able to transform the given dataset into the desired pivot table format. This technique can be extremely useful when dealing with large datasets and the need for aggregated views based on specific criteria. Remember to adapt the query based on your dataset's structure and requirements.

If you have any questions, feel free to leave a comment below!