15. Window Value Functions Flashcards

(7 cards)

1
Q

Return the Sales from previous row.

A

lag(Sales) over(order by OrderDate)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Return the Sales from next row.

A

lead(Sales) over(order by OrderDate)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Analyze the month-over-month (MoM analysis) by finding percentage change in sales between current and previous months.

A
with monthly_sales as (
select
  datetrunc(month, OrderDate) as Month,
  sum(Sales) currentSalesPerMonth
from MyOrders
group by datetrunc(month, OrderDate)
)
select
  Month,
  currentSalesPerMonth,
  lag(currentSalesPerMonth) over(order by Month) as prevSalesPerMonth,
  (currentSalesPerMonth - coalesce(lag(currentSalesPerMonth) over(order by Month), currentSalesPerMonth))* 100.0 / coalesce(lag(currentSalesPerMonth) over(order by Month), 1) as percentChange
from monthly_sales
order by Month;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Order the customers based on the average days between their orders.

Customers with least avg gap between orders tend to be loyal.

A
with customer_orders as (
select
  CustomerID,
  OrderDate,
  lead(OrderDate) over(partition by CustomerID order by OrderDate) as nextOrderDate
from MyOrders
)
select
  CustomerID,
  avg(datediff(day, OrderDate, nextOrderDate)) as avgDaysUntilNextOrder
from customer_orders
group by CustomerID
order by coalesce(avg(datediff(day, OrderDate, nextOrderDate)), 9999);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Find the average shipping duration (in days) per month.

A
with order_shipping as (
select
  OrderID,
  OrderDate,
  ShipDate,
  datediff(day, OrderDate, ShipDate) as shippingDays,
  datetrunc(month, OrderDate) as Month
from MyOrders
)
select
  Month,
  avg(shippingDays) as avgShippingDayPerMonth
from order_shipping
group by Month;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Find the lowest and highest sales value for each product..

A
select
  ProductID,
  max(Sales) as highestSalesPerProduct,
  min(Sales) as lowestSalesPerProduct
from MyOrders
group by ProductID;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Find the OrderIDs of the lowest and highest sales value for each product.

A
with product_sales as (
select
  OrderID,
  ProductID,
  Sales,
  max(Sales) over(partition by ProductID) as MaxSalesPerProduct,
  min(Sales) over(partition by ProductID) as MinSalesPerProduct
from MyOrders
)
select
  *
from product_sales
where Sales = MaxSalesPerProduct or Sales = MinSalesPerProduct;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly