Is there a slick and efficient way to do this query?
Posted in 1999
Topics: General Discussion
Suppose I have a table with an integer column called days. table mytable ( days integer ); Based on this I want to create another table table summarytable ( days integer, total_days integer, cumulative_days integer ); As weird as it seems, days is a unique identifier and there will be one row for each distinct days in the first table, total_days is the sum of the column days in the whole table. cumulative_days is the sum so far for up to that number of days For example Days Total_Days Cumulative Days 2 10 2 3 10 7 5 10 10 Please don't worry about why it's being done this way. I have to do it. Can anyone think of a slick and efficient way to do it, just using SQL? Remember the differing values that days takes on in the first table is an unknown.
>For example
>
>Days Total_Days Cumulative Days
>2 10 2
>3 10 7
>5 10 10
>
>
>Can anyone think of a slick and efficient way to do it, just using SQL?
>
>Remember the differing values that days takes on in the first table is an
>unknown.
>
>
>
Dunno is you would count this as slick and efficient, but:
create temp table mytable ( days integer ) ;
insert into mytable values ( 2 ) ;
insert into mytable values ( 3 ) ;
insert into mytable values ( 5 ) ;
select mt1.days, ( select sum(days) from mytable), sum(mt2.days)
from mytable mt1, mytable mt2
where mt2.days <= mt1.days
group by 1,2
order by 1
gives you:
days (expression) (sum)
2 10 2
3 10 5
5 10 10
(did you mean 5 instead of 7?)
- Paul