Good day,
I am using MS T-SQL in SSMS. I am trying to determine a way to base a window function on a variable or a case statement. I need the window to continue to loop until a certain result happens and then cut the window by those observations. Additionally, perhaps there is better way to do this outside of Windows also, I’ve researched the WHILE expression as a potential options also.
Here is an example dataset:
CREATE TABLE #Items ([Transaction] int, [Item] varchar(10), [Price] money, [Price2] varchar(25), [SaleDate] smalldatetime)
INSERT INTO #Items ([Transaction], [Item], [Price], [Price2], [SaleDate])
VALUES (123,'Blue',1100,'Blue1100','04/10/2018'),
(124,'Blue',1100,'Blue1100','04/09/2018'),
(125,'Blue',1100,'Blue1100','04/09/2018'),
(126,'Blue',3000,'Blue3000','03/27/2018'),
(127,'Blue',1100,'Blue1100','03/27/2018'),
(128,'Blue',1100,'Blue1100','03/27/2018'),
(129,'Blue',1100,'Blue1100','03/27/2018'),
(130,'Blue',1100,'Blue1100','03/27/2018'),
(131,'Red',3328,'Red3328','04/12/2018'),
(132,'Red',3328,'Red3328','04/09/2018'),
(133,'Red',3328,'Red3328','04/06/2018'),
(134,'Red',3328,'Red3328','04/04/2018'),
(135,'Red',3328,'Red3328','04/02/2018'),
(136,'Red',3328,'Red3328','04/02/2018'),
(137,'Yellow',1340,'Yellow1340','04/09/2018'),
(138,'Yellow',1340,'Yellow1340','04/08/2018'),
(139,'Yellow',1340,'Yellow1340','04/08/2018'),
(140,'Yellow',1500,'Yellow1500','04/05/2018'),
(141,'Yellow',1340,'Yellow1340','04/05/2018'),
(142,'Yellow',1340,'Yellow1340','04/05/2018'),
(143,'Yellow',1340,'Yellow1340','04/02/2018'),
(144,'Yellow',1340,'Yellow1340','03/31/2018')
In this case I’d like the window to look at each [Item] sorted by [SaleDate] desc and create the window size by all orders sequential that have the same [Price]. So long as there is no interruption in [Price] the window would be based on those observations. Once that determination is made, I would like to add a column that pulls in the minimum [SaleDate] for those observations in the window.
The desired result is on the last column of this table.
The following a query I’m trying to use but can’t figure out how to get the window to loop:
SELECT
Transaction
, Item
, Price
,Price2
, SaleDate
,(CASE WHEN PRICE2 = LEAD(PRICE2) OVER (ORDER BY Price ASC, SaleDate DESC )
AND LEAD(PRICE2) OVER (ORDER BY Price ASC, SaleDate DESC ) = LEAD(PRICE2) OVER (ORDER BY Price ASC, SaleDate DESC )
THEN MIN(SaleDate) ELSE NULL END) 'StartDate'
FROM #Items
GROUP BY
Transaction
, Item
, Price
,Price2
, SaleDate
Any and all suggetions are welcome! Thank you!