The LAG part was fine, I've used that plenty.
Use window functions partitioned by customer_id to compute the previous order value (LAG), rank (RANK or DENSE_RANK), and percent rank (PERCENT_RANK) for each order. Then sort the final result by order_date descending. Ensure the window frame is correctly defined to include all orders for each customer.
Pro tip: Clarify whether 'previous order' means the immediately preceding order by date or by order_id, and confirm the ranking method (e.g., RANK vs DENSE_RANK) based on business needs. Also, consider how ties in order_date should be handled to avoid ambiguous results.
Identify the need for per-customer calculations: previous order value, rank, and percent rank. Determine the ordering column (order_date) and the partition (customer_id).
Use LAG(order_value) OVER (PARTITION BY customer_id ORDER BY order_date) for previous value. Use RANK() or DENSE_RANK() and PERCENT_RANK() with the same partition and order.
Write a SELECT statement that includes order_id, customer_id, order_value, order_date, city, and the computed window functions. Use a subquery or CTE if needed for clarity.
Add an ORDER BY clause to sort the result by order_date descending, as requested. Ensure the sorting is applied after the window functions are computed.
Check for edge cases (e.g., first order per customer, ties in dates) and consider performance implications of window functions on large datasets.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.