Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To pivot the result of a query in MySQL, you can use the "GROUP BY" clause and "CASE" statement in combination.

Here's an example query that pivots a result set:

SELECT
    your_column1,
    SUM(CASE WHEN your_column2 = 'value1' THEN your_value ELSE 0 END) AS 'Value1',
    SUM(CASE WHEN your_column2 = 'value2' THEN your_value ELSE 0 END) AS 'Value2',
    SUM(CASE WHEN your_column2 = 'value3' THEN your_value ELSE 0 END) AS 'Value3'
FROM
    your_table
GROUP BY
    your_column1

In this example, replace "yourcolumn1" and "yourcolumn2" with the actual column names in your table, and "value1", "value2", and "value3" with the values you want to pivot on. Replace "your_value" with the value you want to aggregate (sum, count, etc.) based on the "CASE" statement.

The "GROUP BY" clause groups the result set by the first column, pivoting the data based on the second column. The "CASE" statement creates a new column for each value you want to pivot on, with the aggregated value displayed in each column.