| Start | ||||
|---|---|---|---|---|
| Simple PIVOT & UNPIVOT (T-SQL) Below is a simple example which shows average item's price of each item per weekday. First, suppose we have a table which keeps daily records of all items' prices. The table should look like below: In order to perform aggregation which is to find the average price per item for each week day, we are going to use the relational operator Result: Lastly, in order to perform the reverse operation of Result: |
||||
| Dynamic PIVOT One problem with the For demonstration we will use a table Creation script for the table will be like: Now if we need to query on the database and figure out number of books in English, Russian, German, Hindi, Latin languages bought into the bookstore every year and present our output in a small report format, we can use PIVOT query like this Special case is when we do not have a full list of the languages, so we'll use dynamic SQL like below |
||||
| Simple Pivot - Static Columns Using Item Sales Table (opens new window) from Example Database (opens new window), let us calculate and show the total Quantity we sold of each Product. This can be easily done with a group by, but lets assume we to 'rotate' our result table in a way that for each Product Id we have a column. Since our 'new' columns are numbers (in the source table), we need to square brackets This will give us an output like
Syntax[first pivoted column] AS ` [second pivoted column] AS ` ... [last pivoted column] AS ` FROM (` RemarksUsing PIVOT and UNPIVOT operators you transform a table by shifting the rows (column values) of a table to columns and vise-versa. As part of this transformation aggregation functions can be applied on the table values. |
Read Article
https://develop.horje.com/learn/1434/reference