The PIVOT and UNPIVOT functions in SQL are incredibly powerful when it comes to transforming data from a row-based format to a column-based format, and vice versa. Today, we're diving deep into the world of UNPIVOT, focusing on a scenario where we unpivot three columns. Let's get started!

Before we leap into the three-column unpivot, let's recap what UNPIVOT does. UNPIVOT rearranges data from one format (like columns) into another (like rows). It's the reverse of PIVOT, which is why we use UNPIVOT to 'unpivot' data. Now, let's tackle our three-column unpivot scenario.

Understanding Three-Column UNPIVOT
When unpivoting, you're transforming data from columns into rows. So, for three columns, you'll end up with three row values per data entry. Understanding this shift in data structure is key to working with UNPIVOT effectively. Let's break this down further.

The PIVOTED Data Structure
Let's assume we have a table, SalesData, with an ID, Product, and 2021Sale_Jan, 2021Sale_Feb, and 2021Sale_Mar columns, where product sales for each month are stored. The PIVOTED data structure looks like this:

| ID | Product | 2021Sale_Jan | 2021Sale_Feb | 2021Sale_Mar |
|---|---|---|---|---|
| 1 | Apples | 10 | 15 | 20 |
UNPIVOTING the Data
Now, we want to UNPIVOT this data. We'll end up with a result set where each row represents one product month and the sale value. Here's how the UNPIVOTED data structure looks:

| ID | Product | Month | Sale |
|---|---|---|---|
| 1 | Apples | January | 10 |
| 1 | Apples | February | 15 |
| 1 | Apples | March | 20 |
As you can see, the data is transformed from a column-based structure to a row-based structure, making it easier to analyze and query.
UNPIVOT Syntax and Examples

Now that we understand the concept, let's look at the UNPIVOT syntax and run through an example. The UNPIVOT function requires a single-column table (on which to UNPIVOT) and a multicolumn table containing the original column names. Let's dive into the syntax and see it in action.
UNPIVOT Syntax



















The UNPIVOT function's syntax is as follows:
- tableColumn: Specifies the column to be unpivoted from the source table.
- valueColumnAS: Specifies the name of the output column that holds the values from the tableColumn.
- otherColumns: Optionally, you can add more column references from the source table.
UNPIVOT Example
Using our SalesData table, here's how we can UNPIVOT the data:
``` SELECT * FROM SalesData UNPIVOT (SaleValue FOR Month IN ([2021Sale_Jan], [2021Sale_Feb], [2021Sale_Mar])) AS unpivotedData ```
The resulting output will match our UNPIVOTED data structure described earlier.
In closing, mastering SQL's UNPIVOT function is a game-changer when working with transformed data. With UNPIVOT, you can seamlessly transform rows into columns, making your data analysis more intuitive and efficient. Keep practicing and expanding your UNPIVOT skillset to unlock new opportunities in your data-driven adventures!