Ask Your Question
0

How can the result of a query be pivoted in MySQL?

asked 2023-06-06 02:16:55 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-06 02:18:02 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 02:16:55 +0000

Seen: 18 times

Last updated: Jun 06 '23