Domanda

I have a SQL result like this:

 name | points
------+-------
 Joe  | 2
 Joe  | 5
 Joe  | 4
 Joe  | 1

Each row represents how many points Joe received per event.

Joe has some basic budget, let's say $100.

What I need to do now is to add a field, which will represent actual budget value, when one point means $10 addition. Something like history of budget growth.

The result should look like this:

 name | points | budget
------+--------+-------
 Joe  | 2      | 120
 Joe  | 5      | 170
 Joe  | 4      | 210
 Joe  | 1      | 220

Usage of a variable seems like the best solution to me, but PostgreSQL is not much friendly with it, so I'm looking for a solution using sumarization of first x rows of the result to get actual points sum since the beginning.

Do you have any idea how to do this without subselecting in each row?

È stato utile?

Soluzione

select name, 
       points,
       100 + sum(points * 10) over (partition by name order by some_timestamp_column) as budget
from the_table
order by some_timestamp_column

You have to have a column that defines a stable sort order over the rows in order to use this.

Altri suggerimenti

Postgres supports this type of accumulation using an OVER clause, like this:

SELECT name, points, SUM(points * 10) OVER (ORDER BY .. order field ..)
FROM .. table ..
GROUP BY .. unique field ..

A cross-database alternative without a sub-select would be to add this column in your host language (php, java, whatever) and not do it in the database.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top