# Pivot Table (From Long to Wide)

Every data scientist, scientist, and engineer should know how to create a pivot table.

π²π°ππ΄ ππ·π΄π½ is the best way to do so in SQL.

π Here are THREE ways to pivot a table for monthly sales.

1οΈβ£ We find the πππΌ of all salesperson each month. Here, use πππΌ(π²π°ππ΄ ππ·π΄π½).

2οΈβ£ We find the average sales of each salesperson each month? Use πΆππΎππΏ π±π + π°π
πΆ(π²π°ππ΄ ππ·π΄π½)

3οΈβ£ Identical to example 1, but using PostgreSQL's FILTER clause.

Some other DBMS supports fancy functions for pivot table. For example, Redshift supports the PIVOT function.

Not sure what DBMS you're using? CASE WHEN works for all cases and is always your safest bet.

π Full example below.