Return the Sales from previous row.
lag(Sales) over(order by OrderDate)
Return the Sales from next row.
lead(Sales) over(order by OrderDate)
Analyze the month-over-month (MoM analysis) by finding percentage change in sales between current and previous months.
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;
Order the customers based on the average days between their orders.
Customers with least avg gap between orders tend to be loyal.
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);
Find the average shipping duration (in days) per month.
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;
Find the lowest and highest sales value for each product..
select ProductID, max(Sales) as highestSalesPerProduct, min(Sales) as lowestSalesPerProduct from MyOrders group by ProductID;
Find the OrderIDs of the lowest and highest sales value for each product.
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;