Я бы сделал это примерно так:
Первые тестовые данные:
DECLARE @tbl TABLE
(
store VARCHAR(4),
item VARCHAR(2),
datekey INT,
onhand INT,
salesUnits INT
)
INSERT INTO @tbl
VALUES
('001','A',50,65,2),
('001','A',51,8,4),
('001','A',52,0,8)
Запрос выглядит так:
;WITH cteTotalSales AS
(
SELECT
SUM(tbl.salesUnits) OVER(PARTITION BY 1) AS TotalSalesUnit,
tbl.store,
tbl.item,
ISNULL(tbl.onhand,0) AS onhand,
tbl.salesUnits,
tbl.datekey
FROM
@tbl AS tbl
), cteLatest AS
(
SELECT
RANK() OVER
(
PARTITION BY cteTotalSales.store,cteTotalSales.item
ORDER BY cteTotalSales.datekey DESC
) AS iRank,
cteTotalSales.store,
cteTotalSales.item,
cteTotalSales.onhand,
cteTotalSales.salesUnits,
cteTotalSales.datekey
FROM
cteTotalSales
WHERE
(cteTotalSales.onhand-cteTotalSales.TotalSalesUnit)>0
)
SELECT
*
FROM
cteLatest
WHERE
iRank=1