📅  最后修改于: 2023-12-03 15:33:01.816000             🧑  作者: Mango
In MySQL, a pivot is a way to transform rows into columns. This can be very useful for data analysis and reporting. In this article, we will discuss how to pivot data in MySQL using SQL queries.
To demonstrate pivot queries, we will use a sample dataset that contains the following fields:
id
- An integer value representing the record IDmonth
- A string value representing the month of the year (Jan
, Feb
, Mar
, etc.)category
- A string value representing a product category (books
, electronics
, clothing
, etc.)sales
- A decimal value representing the total sales for the month and categoryHere is a sample dataset:
| id | month | category | sales | |---:|-------|------------|-------| | 1 | Jan | books | 100.0 | | 2 | Jan | electronics| 200.0 | | 3 | Jan | clothing | 300.0 | | 4 | Feb | books | 150.0 | | 5 | Feb | electronics| 250.0 | | 6 | Feb | clothing | 350.0 | | 7 | Mar | books | 200.0 | | 8 | Mar | electronics| 300.0 | | 9 | Mar | clothing | 400.0 |
To pivot data in MySQL, we will use the CASE
statement and the GROUP BY
clause. Here is a query that pivots the sample dataset by month:
SELECT
category,
SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END) AS 'Jan',
SUM(CASE WHEN month = 'Feb' THEN sales ELSE 0 END) AS 'Feb',
SUM(CASE WHEN month = 'Mar' THEN sales ELSE 0 END) AS 'Mar'
FROM
sales_data
GROUP BY
category;
This query will produce the following output:
| category | Jan | Feb | Mar | |-------------|-------|-------|-------| | books | 100.0 | 150.0 | 200.0 | | electronics | 200.0 | 250.0 | 300.0 | | clothing | 300.0 | 350.0 | 400.0 |
Let's break down the pivot query step-by-step:
category
field and pivot the data by month
using the CASE
statement.SUM
function to calculate the total sales for each category and month.category
field using the GROUP BY
clause.The CASE
statement inside the SUM
function will only add the sales amount for the specified month and category combination. For example, in the first row of the pivot table, the query adds the sales amounts for books
in January, February, and March. The other months are excluded (i.e. the sales amount is zero).
Pivoting data in MySQL using SQL queries can be a powerful tool for analyzing and reporting data. By using the CASE
statement and the GROUP BY
clause, you can transform rows into columns and gain new insights into your dataset.