Transforming Sales Data with SQL PIVOT Operator
Pivot Data Using PIVOT Operator
Write a SQL query to pivot sales data from rows to columns.
Solution:
-- Pivot sales data by year and region.
SELECT *
FROM (
SELECT Region, Year, SalesAmount
FROM SalesData
) AS SourceTable
PIVOT (
SUM(SalesAmount)
FOR Year IN ([2021], [2022], [2023])
) AS PivotTable;
Explanation:
- The goal is to transform sales data from rows (yearly sales per region) into columns (years as separate columns).
- PIVOT Operator : Transforms rows into columns.
- SUM(SalesAmount) : Aggregates sales data.
- FOR Year IN : Specifies the columns to create.
- Pivoting simplifies reporting by organizing data into a more readable format.
- For example, in sales reports, you might use this query to display yearly sales by region in a tabular format.
1. Purpose of the Query :
2. Key Components :
3. Why use Pivoting? :
4. Real-World Application :
Additional Notes:
- Ensure the source data is properly structured before pivoting.
- Use this exercise to teach how to transform data for reporting purposes.
For more Practice: Solve these Related Problems:
- Write a SQL query to pivot monthly sales data into quarterly columns for each region.
- Write a SQL query to transform product-wise sales data from rows into columns for better visualization.
- Write a SQL query to pivot inventory data by warehouse and month to show stock levels in a tabular format.
- Write a SQL query to pivot customer feedback scores by year and category for analysis.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise:Create a Recursive Common Table Expression.
Next SQL Exercise: Unpivot Data Using UNPIVOT Operator.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics