En enkel måde at gøre det på er at bruge en korreleret underforespørgsel i CROSS APPLY
.
Hvis dit bord er mere eller mindre stort, så vil dit næste spørgsmål være, hvordan du gør det hurtigt. Indeks på PlaceB, Product, PickTime INCLUDE (Qty)
skulle hjælpe. Men hvis dit bord er virkelig stort, ville markøren være bedre.
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;
Åh, og hvis (PlaceB, Product, PickTime)
er ikke unik, vil du få noget anderledes resultater end den oprindelige forespørgsel med SUM() OVER
. Hvis du har brug for nøjagtig de samme resultater, skal du bruge en ekstra kolonne (som ID
) for at løse båndene.