I have a price history table that has these 4 fields
- Id
- Date
- Product
- Price
There is a record for ever day for every product. I’m trying to write a query to return a record for the starting price of each product along with a record for each time the price changed.
I tried grouping by price but obviously this breaks when a price changes than at a later date changes back as it will only return 1 record.
I’ve written this query to generate sample data that I am trying to work off
CREATE TABLE #PriceHistory
(
[Id] INT IDENTITY,
[Date] DATETIME ,
[Product] NVARCHAR(30) ,
[Price] MONEY
)
INSERT INTO #PriceHistory([Date],[Product],[Price])
SELECT '20120101', 'Tesco', 1.99
UNION ALL
SELECT '20120102', 'Tesco', 1.97
UNION ALL
SELECT '20120103', 'Tesco', 1.97
UNION ALL
SELECT '20120105', 'Tesco', 1.99
UNION ALL
SELECT '20120104', 'Tesco', 1.99
UNION ALL
SELECT '20120106', 'Tesco', 1.99
UNION ALL
SELECT '20120101', 'BP', 1.99
UNION ALL
SELECT '20120102', 'BP', 1.01
UNION ALL
SELECT '20120103', 'BP', 1.99
SELECT * FROM #PriceHistory
DROP TABLE #PriceHistory
From that sample data the results I’m expecting should be
1 2012-01-01 Tesco 1.99
2 2012-01-02 Tesco 1.97
5 2012-01-04 Tesco 1.99
9 2012-02-11 BP 1.99
8 2012-02-20 BP 1.01
Any ideas on the best way to achieve this?
This query starts with a price, and attempts to find the previous record for the same product with the same price… if there’s no record for the same product at the same price, it returns the record: