25 Advanced SQL Queries - List the first 5 rows of the result set

Many of the examples in this column will be based on the following employee table (employee). Only a few examples will be based on other tables; in these cases the tables will be illustrated along with the examples.

1. WITH

WITH AS phrase, also called subquery part, after defining a SQL fragment, the SQL fragment can be used by the whole SQL statement. Sometimes, with as is used to improve the readability of SQL statements and reduce nesting redundancy.

Two, SQL example sentence

The next SQL query will create a report with employee data for the top five salaries in the company. Such a report must be sorted according to the given criteria; in our example, the sorting criteria would again be salary descending:

WITH employee_ranking AS (
  SELECT
    employee_id,
    last_name,
    first_name,
    salary,
    RANK() OVER (ORDER BY salary DESC) as ranking
  FROM employee
)
SELECT
  employee_id,
  last_name,
  first_name,
  salary
FROM employee_ranking
WHERE ranking <= 5
ORDER BY ranking

The WITH clause in the previous query creates a CTE (Common Table Expression) called employee_ranking, which is a virtual table used in the main query.

A subquery in a CTE uses the function RANK() to obtain the position of each row in the ranking. The clause OVER(ORDER BY salary DESC) indicates how the RANK() value must be calculated. The RANK() function for the row with the highest salary will return 1, and so on.


Finally, in the WHERE of the main query, we ask for those rows where the rank value is less than or equal to 5. This allows us to only get the top 5 rows by rank value. Likewise, we use the ORDER BY clause to display the result set, which is sorted in ascending order.

3. Query results

Guess you like

Origin blog.csdn.net/wyxtx/article/details/131786441