title: PostgreSQL: Select rows until sum-reduction of a single column reaches over a threshold
body: <p>I would like to write a query that takes rows from an ordered table, simultaneously aggregating one column's value until said aggregated value meets a desired threshold.</p>
  
  <p>An additional criteria is that the violating row which passes the threshold should be included in the query results.</p>
  
  <p>I have looked for other solutions done in PostgreSQL, leading me to creating the following query:</p>
  
  <pre><code>SELECT * FROM (
      SELECT *, SUM(amount) OVER (ORDER BY amount DESC) AS running_amount
      FROM public.orders WHERE price = 0.09) AS t
  WHERE t.running_amount &lt;= 15;
  </code></pre>
  
  <p>The issue with this query however is that it represents a PostgreSQL window query, which skips the aggregation of a columns value over all rows if the columns value at a given row is not unique.</p>
  
  <p>Window queries unfortunately do not support taking into account the consideration of distinct-valued columns.</p>
  
  <p>Some alternatives I heard for still making this possible would be through creating a PostgreSQL function, though I have no idea where to start for this sort of aggregation query.</p>
  
  <p>If anyone has any ideas or know-how, I would greatly appreciate it.</p>