Long time reader, first time poster. Hoping some SQL guru can lend me some processing power to solve a SQL problem elegantly and without cursors.
I am trying to create a time line type result set from a data set with money and a Date, where the order in which they appear is important. See sample data and expectation below.
DECLARE @OrderData TABLE(
ID INT IDENTITY,
ProductId INT,
WarehouseId INT,
Cost MONEY,
SaleDate DATETIME
)
INSERT INTO @OrderData
VALUES
(1, 1, 2.71, '2012-02-23 10:01')
,(1, 2, 2.71, '2012-02-23 10:02')
,(1, 1, 2.71, '2012-02-23 10:03')
,(1, 1, 2.71, '2012-02-23 10:04')
,(1, 1, 2.71, '2012-02-23 10:05')
,(1, 1, 2.8, '2012-02-23 10:06')
,(1, 1, 2.9, '2012-02-23 10:07')
,(1, 1, 2.71, '2012-02-23 10:08')
,(1, 1, 2.71, '2012-02-23 10:09')
The result I am looking for is a time line of sales with from and to dates for a product and warehouse combination within it own set of sales. As soon as the sale price changes in the dataset this should spawn a new row in the result set.
Result structure for sample data.
Product, warehouse, minsale date, Max sale date
1,1,2.71, 2012-02-23 10.01, 2012-02-23 10.05
1,1,2.80, 2012-02-23 10.06, 2012-02-23 10.06
1,1,2.90, 2012-02-23 10.07, 2012-02-23 10.07
1,1,2.71, 2012-02-23 10.08, 2012-02-23 10.09
1,2,2.71, 2012-02-23 10.02, 2012-02-23 10.02
Cheers for any help available.
This is a “gaps and islands” problem.
For further information, search for “gaps and islands by itzik ben-gan”