Skip to content
Window Function (copy)
Accompaying Material for Window Function Cheat Sheet
Table introdution: products
products
DataFrameas
df
variable
SELECT product_id, product_name, model_year, list_price FROM products
Table introdution: orders
orders
DataFrameas
df
variable
SELECT order_id, order_date FROM sales.orders
Table introdution: order_items
order_items
DataFrameas
df
variable
SELECT order_id, product_id, discount FROM sales.order_items
GROUP BY VS PARTITION BY
DataFrameas
df
variable
SELECT
model_year,
AVG(list_price) avg_price
FROM products
GROUP BY model_year
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
DataFrameas
df
variable
/* Rank price from LOW->HIGH */
SELECT
product_name,
list_price,
RANK() OVER (ORDER BY list_price ASC) rank
FROM products
DataFrameas
df
variable
SELECT
year(order_date) year,
COUNT(DISTINCT order_id) num_orders
FROM sales.orders
GROUP BY year(order_date)
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