In the realm of data manipulation, SQL offers a powerful tool known as pivoting to transform columns into rows and vice versa. This feature, although not built-in by default, can be achieved using conditional aggregation functions and CASE expressions. Let's explore SQL pivot columns to rows with a practical example.

Imagine you have a table named 'Sales' with the following structure:

- Product: The name of the product
- Year: The year when the sale occurred
- SalesAmount: The total sales amount for that product in that year
Initially, your data might look like this:

| Product | Year | SalesAmount |
|---|---|---|
| ProductA | 2018 | 10000 |
| ProductA | 2019 | 12000 |
| ProductB | 2018 | 8000 |
| ProductB | 2019 | 15000 |
Creating a Pivot Table

A pivot table is an SQL query result that swaps rows and columns for better visualization or analysis. Let's pivot the 'SalesAmount' column from 'Sales' table to display it as distinct 'Year' rows for each 'Product'.
Using CASE Expression
The CASE expression allows us to test certain conditions and return a result accordingly. Here's how to use it for pivoting:

SQL:
```sql SELECT Product, MAX(CASE WHEN Year = 2018 THEN SalesAmount END) AS '2018', MAX(CASE WHEN Year = 2019 THEN SalesAmount END) AS '2019' FROM Sales GROUP BY Product ```
The MAX function is used with CASE expression to treat NULL values from evaluated columns. It replaces these NULLs with 0, thus correctly representing the absence of data for a particular 'Year'.
Result of the Pivoted Table

The SQL query will return the following output:
| Product | 2018 | 2019 |
|---|---|---|
| ProductA | 10000 | 12000 |
| ProductB | 8000 | 15000 |



















Dynamic Pivoting Using Concatenation
If your 'Year' column contains dynamic or varying values, you can use dynamic SQL and string concatenation to build the pivot query. This approach, however, requires knowledge of the database system's dynamic SQL capabilities and can be more complex to implement.
Building the Dynamic SQL
First, create a list of unique 'Year' values and use them to construct the pivot query. Then, execute the query using the 'EXEC' statement in SQL Server or 'PREPARE' and 'EXECUTE' in MySQL.
Executing the Dynamic SQL Query
The dynamic SQL query will return a similar pivoted table as the previous example but with flexible 'Year' column names.
Now that we've seen how to SQL pivot columns to rows, remember that pivoting isn't always the best approach. It largely depends on how your data is structured and how you need to present it. Regardless, being comfortable with pivoting can greatly enhance your SQL skills and give you more control over your data.