You should define an order here.
Assuming you want to order by somecolumn
.
In Oracle
and PostgreSQL 8.4
:
SELECT animal, valx, SUM(valx) OVER (PARTITION BY animal ORDER BY somecolumn) AS valy
FROM mytable
In MySQL
:
SELECT animal, valx,
@valy := CASE WHEN @animal = animal THEN @valy + valx ELSE valx END AS valy,
@animal := animal
FROM (
SELECT @valy = 0,
@animal := NULL
) vars,
mytable
ORDER BY
animal, somecolumn
In SQL Server
, it is one of the rare cases when creating a CURSOR
is more efficient.
All databases (including SQL Server
) support ANSI
syntax:
SELECT animal, valx,
(
SELECT SUM(valx)
FROM mytable mi
WHERE mi.animal = mo.animal
AND mi.somecolumn <= mo.somecolumn
) AS valy
FROM mytable mo
, however, this is not efficient if there are many records in mytable
, execution time grows as O(n^2)