Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since you didn't specify your RDBMS, I will just assume it's Postgresql ;-)</p> <pre><code>select *, sum(amount) over() - sum(amount) over(order by amount) as remainder from tbl; </code></pre> <p>Output:</p> <pre><code>| ID | AMOUNT | REMAINDER | --------------------------- | 3 | 1 | 10 | | 2 | 2 | 8 | | 1 | 3 | 5 | | 4 | 5 | 0 | </code></pre> <p>How it works: <a href="http://www.sqlfiddle.com/#!1/c446a/5" rel="nofollow">http://www.sqlfiddle.com/#!1/c446a/5</a></p> <p>It works in SQL Server 2012 too: <a href="http://www.sqlfiddle.com/#!6/c446a/1" rel="nofollow">http://www.sqlfiddle.com/#!6/c446a/1</a></p> <p>Thinking of solution for SQL Server 2008... </p> <hr/> <p>Btw, is your ID just a mere row number? If it is, just do this:</p> <pre><code>select row_number() over(order by amount) as rn , sum(amount) over() - sum(amount) over(order by amount) as remainder from tbl order by rn; </code></pre> <p>Output:</p> <pre><code>| RN | REMAINDER | ------------------ | 1 | 10 | | 2 | 8 | | 3 | 5 | | 4 | 0 | </code></pre> <p>But if you really need the ID intact and move the smallest amount on top, do this:</p> <pre><code>with a as ( select *, sum(amount) over() - sum(amount) over(order by amount) as remainder, row_number() over(order by id) as id_sort, row_number() over(order by amount) as amount_sort from tbl ) select a.id, sort.remainder from a join a sort on sort.amount_sort = a.id_sort order by a.id_sort; </code></pre> <p>Output:</p> <pre><code>| ID | REMAINDER | ------------------ | 1 | 10 | | 2 | 8 | | 3 | 5 | | 4 | 0 | </code></pre> <p>See query progression here: <a href="http://www.sqlfiddle.com/#!6/c446a/11" rel="nofollow">http://www.sqlfiddle.com/#!6/c446a/11</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload