Introduction
Quick Refresher
PARTITION BY ORDER BY with Ranking
7. RANK() with PARTITION BY ORDER BY
PARTITION BY ORDER BY with Window Frames
Using PARTITION BY ORDER BY with Analytical Functions
Summary and Review

Instruction

Excellent! Let's get started with the new stuff.

In Part 4, you learned ranking functions. These are one place where you can apply PARTITION BY and ORDER BY together.

So far, all the rankings we calculated were performed for all the rows from the query result. With that knowledge, we could have calculated the position of each store in the global network based on their ratings:

SELECT
  Id,
  Country,
  City,
  Rating,
  RANK() OVER(ORDER BY Rating DESC) AS Rank
FROM Store;

Example of RANK()

Now, we can add PARTITION BY to calculate the positions independently for each country:

SELECT
  Id,
  Country,
  City,
  Rating,
  RANK() OVER(PARTITION BY Country ORDER BY Rating DESC) AS Rank
FROM Store;

In this way, we create a separate ranking for each country. Paris and Frankfurt can both get Rank = 1 because there are separate rankings for France and Germany.

Example of RANK() with PARTITION BY

Exercise

For all sales between August 10 and August 14, 2016, show the following information: StoreId, Day, number of customers and rank (based on the number of customers in that store). Name the column Ranking.

Stuck? Here's a hint!

Use PARTITION BY StoreId ORDER BY Customers ASC.