Una forma sencilla de hacerlo es usar una subconsulta correlacionada en CROSS APPLY
.
Si su mesa es más o menos grande, entonces su siguiente pregunta sería cómo hacerla más rápida. Índice en PlaceB, Product, PickTime INCLUDE (Qty)
debería ayudar. Pero, si su tabla es realmente grande, el cursor sería mejor.
WITH
ADVPICK
AS
(
SELECT 'A' as PlaceA,PlaceB, case when PickTime = '00:00' then '07:00' else isnull(picktime,'12:00') end as picktime, cast(Product as int) as product, Prd_Description, -Qty AS Qty FROM t_pick_orders
UNION ALL
SELECT 'A' as PlaceA,PlaceB, '0', cast(Code as int) as product, NULL, Stock FROM t_pick_stock
)
,stock_post_order
AS
(
SELECT
*
FROM
ADVPICK AS Main
CROSS APPLY
(
SELECT SUM(Sub.Qty) AS new_qty
FROM ADVPICK AS Sub
WHERE
Sub.PlaceB = Main.PlaceB
AND Sub.Product = Main.Product
AND T.PickTime <= Main.PickTime
) AS A
)
SELECT
*,
CASE WHEN new_qty > qty THEN new_qty ELSE qty END AS order_shortfall
FROM
stock_post_order
WHERE
new_qty < 0
ORDER BY PlaceB, picktime, product;
Ah, y si (PlaceB, Product, PickTime)
no es único, obtendrá resultados algo diferentes a la consulta original con SUM() OVER
. Si necesita exactamente los mismos resultados, debe usar alguna columna adicional (como ID
) para resolver los empates.