Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL, Looking back several months data for a specific row data 1

Status
Not open for further replies.

proxy00

MIS
Jul 16, 2004
7
CA
Hello,

Could anyone help me on writing a SQL statement to get the following data?

Originally, I have a data set:
Key | Period | rowValue
1 | 2003/01 | 5
2 | 2003/02 | 8
3 | 2003/03 | 20
4 | 2003/04 | 10
5 | 2003/05 | 7
...

And want to have a desired dataset:
Key | Period | rowValue | previous_3_mth_sum
3 | 2003/03 | 20 | 33 (which is 5+8+20)
4 | 2003/04 | 10 | 38 (which is 8+20+10)
5 | 2003/05 | 7 | 37 (which is 7+10+20)
...


Im showing rows for all different periods, but these fields need to be looking back 3 months respective to the specific row, and will therefore not be the same for all rows.
Many Thanks!


 
The basic idea is something like this:
SELECT A.Key, A.Period, A.rowValue,
(SELECT SUM(rowValue) FROM yourTable AS B
WHERE B.Period BETWEEN A.Period - 2 months And A.Period
) AS previous_3_mth_sum
FROM yourTable AS A
WHERE A.Key>=3
The syntax of the following expression A.Period - 2 months depends on your RDBMS.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
hope you saw the smiley ;-)

theta join:
Code:
select t1.key
     , t1.period
     , t1.rowValue
     , sum(t2.rowValue) as previous_3_mth_sum
  from yourtable t1
inner
  join yourtable t2
 where year(t1.period)*12+month(t1.period) 
     between 
       year(t2.period)*12+month(t2.period) 
     and 
       year(t2.period)*12+month(t2.period) +2
group
    by t1.key
     , t1.period
     , t1.rowValue


rudy
SQL Consulting
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top