Skip to content

Accompaying Material for Window Function Cheat Sheet

Table introdution: products

Spinner
DataFrameas
df
variable
SELECT product_id, product_name, model_year, list_price FROM products

Table introdution: orders

Spinner
DataFrameas
df
variable
SELECT order_id, order_date FROM sales.orders 

Table introdution: order_items

Spinner
DataFrameas
df
variable
SELECT order_id, product_id, discount FROM sales.order_items

GROUP BY VS PARTITION BY

Spinner
DataFrameas
df
variable
SELECT
    model_year,
    AVG(list_price) avg_price
FROM products
GROUP BY model_year
Spinner
DataFrameas
df
variable
SELECT
   model_year,
   product_name,
   list_price,
   AVG(list_price) OVER 
     (PARTITION BY model_year) avg_price
FROM products
ORDER BY product_name

ORDER BY

Spinner
DataFrameas
df
variable
/* Rank price from LOW->HIGH  */
SELECT 
product_name, 
list_price,
RANK() OVER (ORDER BY list_price ASC) rank
FROM products
Spinner
DataFrameas
df
variable
   SELECT
    year(order_date) year,
    COUNT(DISTINCT order_id) num_orders
    FROM sales.orders
    GROUP BY year(order_date)
Spinner
DataFrameas
df
variable
/* Rank price from HIGH->LOW  */
SELECT 
product_name, 
list_price,
RANK() OVER (ORDER BY list_price DESC) rank
FROM products

FIRST_VALUE