@dalton_moen
In Presto, you can pivot a table using a combination of the CASE
statement and aggregation functions like MAX
or MIN
. Here's an example of how you can pivot a table in Presto:
- Start by writing a query to select the columns you want to pivot and the values you want to pivot on. For example, let's say you have a table sales with columns product_id, month, and revenue. You want to pivot the table to show total revenue for each product in each month.
1
2
3
4
5
6
7
|
SELECT
product_id,
MAX(CASE WHEN month = 'January' THEN revenue ELSE 0 END) AS January,
MAX(CASE WHEN month = 'February' THEN revenue ELSE 0 END) AS February,
MAX(CASE WHEN month = 'March' THEN revenue ELSE 0 END) AS March
FROM sales
GROUP BY product_id;
|
- In the query above, we are using the CASE statement to check the value of the month column and return the revenue value for that month. We are using the MAX function to aggregate the revenue values for each month. Finally, we are grouping the results by product_id to get the desired pivot table.
- You can customize the pivot table by adding more CASE statements for additional columns to pivot on or using different aggregation functions like SUM or AVG.
- Once you run the query, you will get a pivoted table showing total revenue for each product in each month.
This is a basic example of how you can pivot a table in Presto. You can modify the query based on your specific requirements and the structure of your data.