Not one more, not one less
- O(2ⁿ) · Legendary
- Full plan
- SQL
- window functions
- operations
Problem
The company is splitting 5000 of the year's profits among all its people, Carol included, in proportion to monthly salary. It's paid in whole units, and rounding each person's share doesn't work: the nine rounded shares add up to 5001.
Accounting does it this way. Each person gets their share with the decimals cut off. The units left over are handed out one at a time, starting with whoever lost the biggest fraction; between two equal fractions, whoever comes first alphabetically goes first. Paige's share is 729.54: she has 729 for sure and waits her turn with her .54.
Show each person's name and what they get, in that order, from whoever gets the most to whoever gets the least and, on a tie, by name. The total has to come to exactly 5000, with these salaries and with whatever the salaries are tomorrow.
What it has to return
These rows, in this order
| name | payout |
|---|---|
| Carol | 925 |
| Paige | 729 |
| Mark | 676 |
| Lydia | 534 |
| Samuel | 534 |
| Frank | 463 |
| Grace | 427 |
| Nicole | 374 |
| Rachel | 338 |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
SELECT name, salary,
SUM(salary) OVER () AS total
FROM employeesIt opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(2ⁿ) challenges
- The chain of commandSQL · recursion · strings
- The emptiest shelfSQL · window functions · dates · sets
- The salary in the middleSQL · window functions · grouping
- The store on a streakSQL · window functions · dates
- The Winters oneSQL · recursion · strings · window functions
- Their people's peopleSQL · recursion · grouping