Sikau

PostgreSQL · Day 11 · about 40 min

Project: Staff leaderboard

Windows and views for a live dashboard.

Who's leading?

Build the view behind a staff leaderboard: totals per person, rank within their branch and overall, and their share of the branch's sales.

Total first, then rank

A leaderboard view is a small example of a big idea: put reusable logic in the database once, give it a clear name, and let every dashboard and report select from it instead of rebuilding the same calculation.

Window functions run after GROUP BY, so you can't rank staff by a total that doesn't exist yet in the same step. The clean pattern is two steps: a CTE that sums each person's sales, then a SELECT that ranks those totals. Each step is simple to check on its own, and the final view reads like the spec.

WITH totals AS (
  SELECT branch, staff, sum(amount) AS total
  FROM sales
  GROUP BY branch, staff
)
SELECT branch, staff, total,
       rank() OVER (PARTITION BY branch ORDER BY total DESC) AS branch_rank,
       rank() OVER (ORDER BY total DESC) AS overall_rank
FROM totals;

The rest of this lesson

  • Shares of a wholeexplain
  • Checking the leaderboardexplain
  • Column to expressionmatch
  • Ties in rank()predict
  • The leaderboard viewchallenge
  • Badge quizquiz
  • Unit 2 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of PostgreSQL