You could do this with a subquery:
SELECT *
FROM (select id,
somedate,
somevalue,
sum(somevalue) over(order by somedate) as runningtotal
from TestTable
)sub
WHERE somedate > '2009-02-20'
Pergunta
I am trying to calculate a running total on a table, while limiting the number of rows returned by the query.
My table looks something like this:
create table TestTable
(
id int,
somedate date,
somevalue int
)
insert into TestTable values
(45, '01/Jan/09', 3),
(23, '08/Jan/09', 5),
(12, '02/Feb/09', 0),
(77, '14/Feb/09', 7),
(39, '20/Feb/09', 34),
(33, '02/Mar/09', 6)
And I can get all the rows with a running total of "value" like this:
select id,
somedate,
somevalue,
sum(somevalue) over(order by somedate) as runningtotal
from TestTable
I want to limit the results returned to a specific date range, while still having the running total get computed from the beginning of the table. So, for example, I want all rows with a date on or after 20/Feb/09. Then, I would want my result set to look like:
39 20/Feb/09 49
33 02/Mar/09 55
But if i just do a where somedate > 20/Feb/09
, then I get
39 20/Feb/09 34
33 02/Mar/09 40
which is not what I want, because it's computing the running total only within the window.
Is there a way to get what I want?
Solução
You could do this with a subquery:
SELECT *
FROM (select id,
somedate,
somevalue,
sum(somevalue) over(order by somedate) as runningtotal
from TestTable
)sub
WHERE somedate > '2009-02-20'