I have a table with 3 column
+---------------+-------------------------+-------+ | InstrumentId | Date | Price | +---------------+-------------------------+-------+ | 39 | 2012-10-31 00:00:00.000 | 150 | | 39 | 2012-11-01 00:00:00.000 | 160 | | 39 | 2012-11-01 00:00:00.000 | 200 | | 40 | 2012-10-31 00:00:00.000 | 150 | | 40 | 2012-11-01 00:00:00.000 | 140 | | 40 | 2012-11-01 00:00:00.000 | 200 | | 50 | 2012-10-31 00:00:00.000 | 150 | | 50 | 2012-11-01 00:00:00.000 | 150 | | 50 | 2012-11-01 00:00:00.000 | 150 | +---------------+-------------------------+-------+
I need to recive next result:
+--------------+-------+ | InstrumentId | Price | +--------------+-------+ | 39 | 200 | | 40 | 0 | | 50 | 150 | +--------------+-------+
rules:
if price for same InstrumentId is growing or is equal => return last price (that means every next price greater or equal to a previous price.
For instance Id 39: 150 <= 160 <= 200 => return 200)
if any price for same InstrumentId is less than previous => return 0 (see instrumentId 40)
I can do that with a cursor… but I think that exist a simply workaround to do this.
Any ideas?
test data:
DECLARE @table TABLE(
instrumentId INT NOT NULL,
priceListDate DATETIME NOT NULL,
price DECIMAL NOT NULL
)
INSERT INTO @table
(
instrumentId,
priceListDate,
price
)
VALUES( 39, '2012-10-31 00:00:00.000', 150),
(39,'2012-11-01 00:00:00.000', 160),
(39,'2012-11-01 00:00:00.000', 200),
(40,'2012-10-31 00:00:00.000', 150),
(40,'2012-11-01 00:00:00.000', 140),
(40,'2012-11-01 00:00:00.000', 200),
(50,'2012-10-31 00:00:00.000', 150),
(50,'2012-11-01 00:00:00.000', 150),
(50,'2012-11-01 00:00:00.000', 150)
Let me know if this works ok. I’m guessing you won’t ever have a price = -1 in your table, I think that would cause problems for the current solution.
It might seem a bit convoluted but the basic idea is to determine the next and previous row of the current on in order to test the value of the price column for that row.