Skip to main content
tag
Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101
Source Link
h3n
  • 133
  • 2

SQL Sub-query with running total optimization

The codes below get the rows of data until it reaches the total running quantity limit.

Notice that the SQL uses sub-query. select *, sum(Quantity) over (order by id) as RunningQty from #PurchaseOrderProducts. I'm worried that the sub-query would get all the data from the table. Is there a way to improve the performance?

CREATE TABLE #PurchaseOrderProducts
(
    Id int, 
    Product varchar(10), 
    Quantity int
)

INSERT INTO #PurchaseOrderProducts VALUES (1, 'Item A', 5)
INSERT INTO #PurchaseOrderProducts VALUES (2, 'Item B', 1)
INSERT INTO #PurchaseOrderProducts VALUES (3, 'Item C', 8)
INSERT INTO #PurchaseOrderProducts VALUES (4, 'Item D', 2)
INSERT INTO #PurchaseOrderProducts VALUES (5, 'Item E', 1)

SELECT P.*
FROM (select *, sum(Quantity) over (order by id) as RunningQty
      from #PurchaseOrderProducts
     ) P
WHERE P.RunningQty - Quantity < 12;