What is the usage of the SQL pivot function?
The PIVOT function in SQL is used to transform row data into column data. Essentially, it aggregates a query result containing multiple columns by specifying one or more columns, using their values as the names of new columns and filling those columns with the values of other columns.
The PIVOT function is typically used in conjunction with aggregate functions (such as SUM, COUNT, MAX, etc.) to summarize data. It is useful for situations where certain row data needs to be displayed as columns, for example summarizing sales data by different products and displaying the sales figures for each product as columns.
Here is the syntax for the PIVOT function:
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
FROM <table>
PIVOT (
<aggregation function>(<column to aggregate>)
FOR <column to pivot>
IN ([first pivoted value], [second pivoted value], ...)
) AS <alias>
In this case,