Longest Gap Between Orders
For customers 1 to 12, return customer_id and longest_gap_days: the largest number of days between two consecutive orders (in date order, ties by order_id). Customers with fewer than two orders are not returned. Sort by customer_id.
Hint 1
Compute days since previous order with LAG in a CTE, then take MAX per customer.
Reference solution
WITH gaps AS (
SELECT customer_id,
JULIANDAY(order_date)
- JULIANDAY(LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date, order_id)) AS gap
FROM orders
WHERE customer_id BETWEEN 1 AND 12
)
SELECT customer_id, CAST(MAX(gap) AS INTEGER) AS longest_gap_days
FROM gaps
WHERE gap IS NOT NULL
GROUP BY customer_id
ORDER BY customer_id;
You cannot nest a window function inside an aggregate (MAX(LAG(...)) is not allowed), so compute the gaps in a first step and aggregate them in the second. A customer with a single order has no gap: LAG gives NULL, the WHERE gap IS NOT NULL removes that row, and the customer disappears from the result, exactly as the task says. The maximum of consecutive gaps is not the same as last date minus first date.