Home > Database > Mysql Tutorial > How to Pivot MySQL Column Data into Rows: A SQL Query Approach?

How to Pivot MySQL Column Data into Rows: A SQL Query Approach?

Mary-Kate Olsen
Release: 2024-12-19 14:06:12
Original
105 people have browsed it

How to Pivot MySQL Column Data into Rows: A SQL Query Approach?

Pivoting MySQL Column Data as Rows

When working with MySQL, a common task is to transform data from a column format into a row format. This process, known as pivoting, can be particularly useful for presenting data in a more user-friendly and easily digestible manner.

Consider the following scenario:

You have three tables:

  • Question table (id, question)
  • Results table (id, user_id, job_id)
  • Answers table (id, answer, fk_question_id, fk_result_id)

The Questions table contains a list of possible questions. The Results table associates users with job results. The Answers table stores user responses to the questions for each result.

Your goal is to display the question answers as columns for each result set. The desired outcome is as follows:

+-----------+---------+--------+-------------+----------+----------+
| result_id | user_id | job_id | Is it this? | Or this? | Or that? |
+-----------+---------+--------+-------------+----------+----------+
| 1         | 1       | 1      | Yes         | No       | Maybe    |
| 2         | 1       | 3      | Maybe       | No       | Maybe    |
| 3         | 2       | 3      | Yes         | Yes      | No       |
+-----------+---------+--------+-------------+----------+----------+
Copy after login

To achieve this transformation, you can utilize the following MySQL query:

SELECT  a.ID,
        a.user_ID,
        a.job_id,
        MAX(CASE WHEN c.question = 'Is it this?' THEN b.answer END) 'Is it this?',
        MAX(CASE WHEN c.question = 'Or this?' THEN b.answer END) 'Or this?',
        MAX(CASE WHEN c.question = 'Or that? ' THEN b.answer END) 'Or that? '
FROM    Results a
        INNER JOIN Answers b
            ON a.id = b.fk_result_id
        INNER JOIN Question c
            ON b.fk_question_id = c.ID
GROUP   BY a.ID,
        a.user_ID,
        a.job_id
Copy after login

This query employs a combination of INNER JOIN statements and MAX() and CASE functions to aggregate the answers for each question and result combination. It effectively pivots the data from a column format to a row format, allowing you to visualize the answers as columns.

To execute this query, replace the table and column names in the FROM and JOIN clauses with your actual table and column names. Once executed, the query will return the pivoted data in the desired format.

Alternatively, if you have a large number of questions, you can use a dynamic SQL version of the query to handle an unknown number of questions. This dynamic approach is particularly useful when the number of columns in the pivoted result is unknown or changes frequently. The dynamic SQL version is as follows:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN c.question = ''',
      question,
      ''' then b.answer end) AS ',
      CONCAT('`',question,'`')
    )
  ) INTO @sql
FROM Question;

SET @sql = CONCAT('SELECT  a.ID,
                            a.user_ID,
                            a.job_id, ', @sql, ' 
                    FROM    Results a
                            INNER JOIN Answers b
                                ON a.id = b.fk_result_id
                            INNER JOIN Question c
                                ON b.fk_question_id = c.ID
                    GROUP   BY a.ID,
                            a.user_ID,
                            a.job_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Copy after login

The above is the detailed content of How to Pivot MySQL Column Data into Rows: A SQL Query Approach?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template