🪟 It's time for @* Marketing Cloud Engagement * SQL Window Functions: https://mateuszdabrowski.pl/docs/salesforce/marketing-cloud-engagement/sql/sql-window-functions/
Built for SQL power users, with a real-life example in every section: the latest open of each subscriber, the days between two orders, your top 10 customers. Most of us build those with a chain of Query Activities and a staging Data Extension. Deduplication, top N lists and running totals - window functions do it in one query, with a few traps along the way:
🔵 Nearly everything works.
ROW_NUMBER, RANK, NTILE, LAG and running totals all run in MCE. Even IGNORE NULLS from SQL Server 2022 works, so the last coupon each subscriber used takes a single function.
🟠 Ties pick a random winner.
ROW_NUMBER over two orders from the same day keeps either of them, and the next run can keep the other. There is no error, and your Data Extension changes between runs. End every ORDER BY inside OVER with a unique column.
🔴 Filtering needs a subquery.
WHERE ROW_NUMBER() OVER (...) = 1 fails with "Windowed functions can only appear in the SELECT or ORDER BY clauses." The usual fix, a WITH, fails too, as the MCE syntax validation wants SELECT as the first word (sic!). A subquery in FROM does the job.
Encountering issues? My free and open source
SQL Studioflags them before you run anything and offers fixes with one click.
Writing SQL with Claude instead? The newly updated
SF MCE SQL skill from SQL Studio gives Claude the same rules.