I have a SQL query that uses a Common Table Expression (CTE) with window functions, and I need to implement it using Kotlin's Exposed DSL. Since Exposed doesn't have built-in CTE support, I'm looking for a way to create custom CTEs.
Query:
WITH ranked_orders AS (
SELECT
customer_id,
order_date,
total_amount,
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date DESC) as rank_num
FROM orders
)
SELECT
customer_id,
order_date,
total_amount
FROM ranked_orders
WHERE rank_num <= 3;
Based on this JetBrains video (29:00) https://www.youtube.com/watch?v=xgfeqj8UyVA&lc=Ugz_N4GGefP6accqKbl4AaABAg, it seems Exposed provides the tools to implement CTEs ourselves, but I haven't found concrete examples of how to do it. They created custom CTE, haven't provided code. Any working code examples would be greatly appreciated!
.whereworks on an aliased query.