Defining window functions
Continuing with the discussion on window functions, consider, for instance, that you want to find the first customers of ZoomZoom to offer customer loyalty promotions. To put it more technically, this means you want to rank every customer in order according to the date they became a customer, with the earliest customer being ranked 1, the second-earliest customer being ranked 2, and so on. You can get all the customers using the following query:
SELECT first_name, last_name, date_added
FROM customers
ORDER BY date_added;
You can order the customers from the earliest to the most recent, copy the output to an Excel spreadsheet, and assign a row number to each row so that you have the rank for each customer. However, this is not automated and is error-prone. Here, SQL provides several ways using which you can achieve this ranking. Later in this chapter, you will learn how to assign numbers to ordered records by using the RANK window function. But before...