Data Lake • Write your own SQL

Best in each group

What are the top 2 products in every region?

Try this

  • Run this on my data lake: SELECT region, product, SUM(amount) AS revenue FROM samples.shop_orders GROUP BY region, product QUALIFY rank() OVER (PARTITION BY region ORDER BY SUM(amount) DESC) <= 2 ORDER BY region, revenue DESC

In plain words

What is it?

A normal top list gives winners overall. This gives winners inside each region.

How does it work?

First it adds up each product in each region. rank() numbers them 1, 2, 3 inside their region, and QUALIFY keeps only numbers 1 and 2.

Good to know

QUALIFY saves you from wrapping one question inside another. If two products tie, both are kept.

Then try

Sales month by month (ask for all rows)

  • Run this on my data lake: SELECT date_trunc('month', order_date) AS month, SUM(amount) AS revenue FROM samples.shop_orders GROUP BY 1 ORDER BY 1