PostgreSQL

Chapter 7 - DQL (Data Query Language)

GROUP RANK

In PostgreSQL, the concept of "GROUP RANK" typically involves ranking groups of rows within a result set according to specific criteria. This is commonly achieved using window functions in conjunction with GROUP BY Window functions are useful for performing calculations across a set of table rows that are somehow related to the current row.

Here’s a step-by-step guide on how to use PostgreSQL to rank groups of rows:

  1. Understand the Context: Group ranking is often used to rank items within categories. For example, you might want to rank customers based on their total transaction amounts within each branch of a bank.
  2. Use of Window Functions: PostgreSQL provides window functions such as ROW_NUMBER(), RANK(), and DENSE_RANK() to assign ranks to rows within partitions of a result set.
  3. Example Query: Suppose you have a transactions table and you want to rank customers based on the total amount they have transacted, grouped by their branch.
    -- Example table structure:
    -- transactions (id, customer_id, branch_id, amount)
    
    SELECT
    customer_id,
        branch_id,
    SUM(amount) AS total_amount,
    RANK() OVER (PARTITION BY branch_id ORDER BY SUM(amount) DESC) AS rank
    FROM
    transactions
    GROUP BY
    customer_id, branch_id
    ORDER BY
    branch_id, rank;
  4. Explanation:
    • PARTITION BY branch_id divides the result set into partitions (one for each branch).
    • ORDER BY SUM(amount) DESC orders the rows within each partition by the total transaction amount in descending order.
    • RANK() assigns a rank to each row within its partition based on the specified order.
  5. Common Use Cases:
    • Ranking employees by sales performance within each department.
    • Ranking products by sales volume within each category.

By understanding and applying these concepts, you can effectively rank groups of data in PostgreSQL, which is valuable for generating reports and analyzing grouped datasets.

  • Tansy SQL Course - GROUP RANK - Video Thumbnail

    TEST CODE

    In PostgreSQL, to utilize the RANK() function to assign rankings to employee salaries within specific departments, you can use the following query:

    SELECT
      employee_number,
      department,
      salary,
      RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS salary_rank
    FROM
      org_employee;
  • SQL GROUP RANK

    Utilize the RANK() function to assign rankings to employee salaries within specific departments.

    RAW EMPLOYEE DATA

    Image Description

    QUERY DATA MAPPING

    Image Description

    This image demonstrates that we need to rank each salary within a specified department. In PostgreSQL, we use PARTITION BY for this purpose.

    QUERY OUT PUT

    Image Description

    Here you can see ranking of each salary with in a given department.

    Comments(0 comments)

    Comments Not Found