Selected topic
Advanced Sql
Prefer practical output? Use related tools below while reading.
sql
SELECT column1, [column2], ..., [columnN]
FROM table_name
PIVOT (
aggregate_function (sum | avg | max | min | count)
FOR column_name IN ([value1], [value2], ..., [valueN])
)
Sales with the following data:
markdown
+--------+---------+
| Product| Sales |
+--------+---------+
| A | 100 |
| B | 200 |
| C | 300 |
| A | 150 |
| B | 250 |
| C | 350 |
+--------+---------+
We want to pivot this data to show the sales for each product in separate columns. We can use the following query:
sql
SELECT Product, [A], [B], [C]
FROM Sales
PIVOT (
SUM(Sales)
FOR Product IN ([A], [B], [C])
);
Result:
markdown
+--------+----+----+----+
| Product| A | B | C |
+--------+----+----+----+
| A | 250| 0 | 0 |
| B | 0 | 450| 0 |
| C | 0 | 0 | 650|
+--------+----+----+----+
sql
SELECT column1, [column2], ..., [columnN]
FROM table_name
UNPIVOT (
value_column
FOR column_name IN ([value1], [value2], ..., [valueN])
)
Sales with the following data:
markdown
+--------+----+----+----+
| Product| A | B | C |
+--------+----+----+----+
| A | 250| 0 | 0 |
| B | 0 | 450| 0 |
| C | 0 | 0 | 650|
+--------+----+----+----+
We want to unpivot this data to show each product and its corresponding sales in separate rows. We can use the following query:
sql
SELECT Product, Sales
FROM Sales
UNPIVOT (
Sales
FOR Product IN ([A], [B], [C])
);
Result:
markdown
+--------+------+
| Product| Sales |
+--------+------+
| A | 250 |
| B | 450 |
| C | 650 |
+--------+------+
I hope this helps! Let me know if you have any questions or need further clarification.