I have some data in a table that looks similar to this:
Item Date Price A 8/29/2012 $3 B 8/29/2012 $23 C 8/29/2012 $10 A 8/30/2012 $4 B 8/30/2012 $25 C 8/30/2012 $11 A 8/31/2012 $3 B 8/31/2012 $22 C 8/31/2012 $8 A 9/01/2012 $3 B 9/01/2012 $26 C 9/01/2012 $9 A 9/02/2012 $3 B 9/02/2012 $24 C 9/02/2012 $9
I need to write a query that identifies that price for A hasn’t changed
since 8/30/2012, price for item C hasn’t changed since 9/01/2012, and
to return the number of days elapsed for both (we’re looking for items
with non-moving prices). I can’t use CTE, or cursors, or separately created
temp tables (select into, etc) because of the limitations of the web report
tool this sql needs to run in. I can only use a ‘basic’ single pass select query
(subqueries will work though). Does anyone have any cunning ideas on how to
achieve this??
My first attempt was to group by Item and Price, where price is the same as
the latest price, having count > 2, identifying the min date and doing a datediff
between min date and getdate. However this just identifies the first instance of
that price, it doesn’t take into account any subsequent rows that might have a
different price. Hope that makes sense.
I’ve given both types of ages and account for items that exist only once in the table (they don’t have an old date). Please let us know how close this is.
UPDATE: I had to correct the date calculation in “PriceAgeToNow”, and I’ve also tried to filter out records that are have only had a new price for 1 day. Here is the SQL Fiddle.