Using SQL to average data within a certain range
Posted on 2011-03-22
I have a number of date-stamped sales transactions each of which belongs to a store A, B, C, etc...
The earliest and latest transactions for each store can all be different but there will always be transactions for the whole period per store (e.g. for any store, if the first transaction is on 14/01/2011 and the last is on 20/03/2011 then there will be a full set of transactions for the whole period).
I want to look at the average growth in sales values between different periods e.g. from January 2011 to February 2011.
I'm sure you can see the problem:
To do this I must consider only transactions from stores that have an earliest transaction of 01/01/2011 or before and a latest transaction of 28/02/2011 or later.
In principle I could:
1) Look up each stores earliest and latest transactions
2) Add a conditional to my SQL query that includes only valid stores
The problem with this is that I have around 2000 stores and so my conditional could end up being, for example, 566 additional "AND StoreCode=" clauses which does not seem very efficient.
I would have thought that there would be a pattern to solve this problem as it must be a common concern in generating many like-for-like growth statistics?