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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stored Procedure Help - Challenge

Status
Not open for further replies.

cpuphantom

IS-IT--Management
Jan 8, 2001
58
0
0
US
Here is a challenging algorithm I need help with:

I have a table called tbNumbers that stores billings values per user per office. Each record has a datestamp. Here is an example of some data from the table:

Code:
[b]id[/b]     [b]user_id[/b]     [b]office_id[/b]     [b]billing[/b]     [b]datestamp[/b]
1      15          1          10000          1/14/2006
2      19          1          10000          1/14/2006
3      21          1          10000          1/14/2006
4      34          6          10000          1/14/2006
5      25          6          10000          1/14/2006
6      15          1          10000          1/21/2006
7      19          1          10000          1/21/2006
8      21          1          10000          1/21/2006
9      34          6          10000          1/21/2006
10     25          6          10000          1/21/2006

Basically, the records all have Saturday datestamps, with the occasional record in between (for the end of the month).

What I need to do is get a report of trailing periods. So say for a three month period of 1/1 through 3/31... I would need a row for each Saturday date... with a sum of the billings field for the previous 6 months before each date.

So for 1/14 it would be a sum of billings for all records between 1/14/06 and 7/14/05 (6 months prior), and then on 1/21... it would display a sum of billings for 7/21/05 through 1/21/06 and so on for each week between the selected time period of 1/1/06 through 3/31/06.

I was able to do it... but it wasn't very clean and there has to be a better way. Here's how I did it:

Code:
select 
	(select sum(b.billings) from tbNumbers as B where b.datestamp between dateadd(m, -6, a.datestamp) and a.datestamp and b.office_id = a.office_id) as sum_bill,
	a.datestamp
from
	tbNumbers as A
where
	a.office_id = 1 and
	a.datestamp between '1/1/2003' and '12/31/2003' and
	datepart(dw, a.datestamp) = 7 
group by
	a.datestamp,
	a.office_id
order by
	a.datestamp

Any ideas and help would be appreciated... I'll need to pass to this stored procedure a list of user_id's... because it may be for a whole office, or multiple offices, or even a couple users.

Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top