Query to retrieve x number of rows based on quantity from another table
Edit: I'm using SQL Server 2014
I need to write a query to return only the number of rows where the sum of the quantity covers a quantity from a different table.
I'm working with two tables. An inventory table and a purchase history table. I want to return the rows from the purchase history table for a specific inventory item where the sum of the quantities in said rows covers the quantity on hand from the inventory table, ordered by newest purchase date to oldest.
Example:
Inventory table
-------------------
| SKU | Quantity |
-------------------
| 1234 | 10 |
-------------------
Purchase history table
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
| 1234 | 4 | 2018-10-01 |
| 1234 | 12 | 2018-09-01 |
--------------------------------
This is the result I'm expecting
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
--------------------------------
Because 5 + 3 + 9 covers the 10 we have in stock.
Maybe I'm missing something simple, but I just can't think of how to get the results to stop at, in this specific case, the third record.
Also, I would really prefer to avoid using loops, if possible.
Any help would be greatly appreciated, because I just can't wrap my head around this one.
sql-server sql-server-2014
New contributor
add a comment |
Edit: I'm using SQL Server 2014
I need to write a query to return only the number of rows where the sum of the quantity covers a quantity from a different table.
I'm working with two tables. An inventory table and a purchase history table. I want to return the rows from the purchase history table for a specific inventory item where the sum of the quantities in said rows covers the quantity on hand from the inventory table, ordered by newest purchase date to oldest.
Example:
Inventory table
-------------------
| SKU | Quantity |
-------------------
| 1234 | 10 |
-------------------
Purchase history table
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
| 1234 | 4 | 2018-10-01 |
| 1234 | 12 | 2018-09-01 |
--------------------------------
This is the result I'm expecting
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
--------------------------------
Because 5 + 3 + 9 covers the 10 we have in stock.
Maybe I'm missing something simple, but I just can't think of how to get the results to stop at, in this specific case, the third record.
Also, I would really prefer to avoid using loops, if possible.
Any help would be greatly appreciated, because I just can't wrap my head around this one.
sql-server sql-server-2014
New contributor
1
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32
add a comment |
Edit: I'm using SQL Server 2014
I need to write a query to return only the number of rows where the sum of the quantity covers a quantity from a different table.
I'm working with two tables. An inventory table and a purchase history table. I want to return the rows from the purchase history table for a specific inventory item where the sum of the quantities in said rows covers the quantity on hand from the inventory table, ordered by newest purchase date to oldest.
Example:
Inventory table
-------------------
| SKU | Quantity |
-------------------
| 1234 | 10 |
-------------------
Purchase history table
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
| 1234 | 4 | 2018-10-01 |
| 1234 | 12 | 2018-09-01 |
--------------------------------
This is the result I'm expecting
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
--------------------------------
Because 5 + 3 + 9 covers the 10 we have in stock.
Maybe I'm missing something simple, but I just can't think of how to get the results to stop at, in this specific case, the third record.
Also, I would really prefer to avoid using loops, if possible.
Any help would be greatly appreciated, because I just can't wrap my head around this one.
sql-server sql-server-2014
New contributor
Edit: I'm using SQL Server 2014
I need to write a query to return only the number of rows where the sum of the quantity covers a quantity from a different table.
I'm working with two tables. An inventory table and a purchase history table. I want to return the rows from the purchase history table for a specific inventory item where the sum of the quantities in said rows covers the quantity on hand from the inventory table, ordered by newest purchase date to oldest.
Example:
Inventory table
-------------------
| SKU | Quantity |
-------------------
| 1234 | 10 |
-------------------
Purchase history table
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
| 1234 | 4 | 2018-10-01 |
| 1234 | 12 | 2018-09-01 |
--------------------------------
This is the result I'm expecting
--------------------------------
| SKU | Quantity | Date |
--------------------------------
| 1234 | 5 | 2019-01-01 |
| 1234 | 3 | 2018-12-01 |
| 1234 | 9 | 2018-11-01 |
--------------------------------
Because 5 + 3 + 9 covers the 10 we have in stock.
Maybe I'm missing something simple, but I just can't think of how to get the results to stop at, in this specific case, the third record.
Also, I would really prefer to avoid using loops, if possible.
Any help would be greatly appreciated, because I just can't wrap my head around this one.
sql-server sql-server-2014
sql-server sql-server-2014
New contributor
New contributor
edited Jan 18 at 16:34
Sean Lange
24.7k21835
24.7k21835
New contributor
asked Jan 18 at 16:23
BrownJenkinBrownJenkin
11
11
New contributor
New contributor
1
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32
add a comment |
1
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32
1
1
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32
add a comment |
3 Answers
3
active
oldest
votes
Another option is a CROSS APPLY
Example
Select B.*
From Inventory A
Cross Apply (
Select *
From (
Select *,RB = sum([Quantity]) over (Partition By SKU Order by Date Desc) - Quantity
From Purchase
Where SKU=A.SKU
) B1
Where RB<=A.Quantity
) B
add a comment |
you can do it with an INNER JOIN
when summing the rows, I use IIF to set the current row to zero in the sum, because I don't want to include that in the check
begin try drop table #Phistory end try begin catch end catch;
begin try drop table #inventory end try begin catch end catch;
SELECT 1234 SKU,5 Quantity, cast('20190101' as date) [date] into #Phistory;
INSERT #Phistory (SKU, Quantity,[date]) VALUES (1234,3,'20181201'), (1234,9,'20181101'),(1234,4,'20181001'),(1234,12,'20180901'),(1235,3,'20181201'), (1235,9,'20181101'),(1235,4,'20181001'),(1235,12,'20180901'),(1235,500,'20180801'),(1235,50,'20180601');
select 1234 SKU, 10 quantity into #inventory;
insert #inventory values(1235,99);
SELECT p1.SKU,
p1.Quantity,
p1.[Date],
SUM(p2.quantity) RunningTotal
FROM #Phistory p1
JOIN #PHistory p2
ON p1.SKU = p2.sku and p2.date >= p1.date
GROUP BY p1.SKU,
p1.Quantity,
p1.[Date]
HAVING SUM(IIF(p1.date = p2.date , 0 , p2.quantity))
<= (SELECT inv.quantity from #inventory inv where inv.sku = p1.sku)
order by p1.sku,p1.date DESC;
add a comment |
I think you could probably do something like the following (untested):
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity <= i.quantity
The idea here is to calculate the running sum in the inner query, then join with your inventory table. I've made an assumption with the ORDER BY date, but you could adjust that.
Edit: So based on the comment that you want the first N rows that use all your inventory (as opposed to the first N rows that don't exceed your inventory) I think you could do something like:
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity < i.quantity
This is the same basic idea but the running sum is switched to only count previous rows (not include the current row) and the join uses < rather than <=. That way if the previous rows quantity didn't total to inventory yet, you will include the next row (even if that total now exceeds inventory).
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
BrownJenkin is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54257848%2fquery-to-retrieve-x-number-of-rows-based-on-quantity-from-another-table%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Another option is a CROSS APPLY
Example
Select B.*
From Inventory A
Cross Apply (
Select *
From (
Select *,RB = sum([Quantity]) over (Partition By SKU Order by Date Desc) - Quantity
From Purchase
Where SKU=A.SKU
) B1
Where RB<=A.Quantity
) B
add a comment |
Another option is a CROSS APPLY
Example
Select B.*
From Inventory A
Cross Apply (
Select *
From (
Select *,RB = sum([Quantity]) over (Partition By SKU Order by Date Desc) - Quantity
From Purchase
Where SKU=A.SKU
) B1
Where RB<=A.Quantity
) B
add a comment |
Another option is a CROSS APPLY
Example
Select B.*
From Inventory A
Cross Apply (
Select *
From (
Select *,RB = sum([Quantity]) over (Partition By SKU Order by Date Desc) - Quantity
From Purchase
Where SKU=A.SKU
) B1
Where RB<=A.Quantity
) B
Another option is a CROSS APPLY
Example
Select B.*
From Inventory A
Cross Apply (
Select *
From (
Select *,RB = sum([Quantity]) over (Partition By SKU Order by Date Desc) - Quantity
From Purchase
Where SKU=A.SKU
) B1
Where RB<=A.Quantity
) B
answered Jan 18 at 16:50
John CappellettiJohn Cappelletti
45.5k62546
45.5k62546
add a comment |
add a comment |
you can do it with an INNER JOIN
when summing the rows, I use IIF to set the current row to zero in the sum, because I don't want to include that in the check
begin try drop table #Phistory end try begin catch end catch;
begin try drop table #inventory end try begin catch end catch;
SELECT 1234 SKU,5 Quantity, cast('20190101' as date) [date] into #Phistory;
INSERT #Phistory (SKU, Quantity,[date]) VALUES (1234,3,'20181201'), (1234,9,'20181101'),(1234,4,'20181001'),(1234,12,'20180901'),(1235,3,'20181201'), (1235,9,'20181101'),(1235,4,'20181001'),(1235,12,'20180901'),(1235,500,'20180801'),(1235,50,'20180601');
select 1234 SKU, 10 quantity into #inventory;
insert #inventory values(1235,99);
SELECT p1.SKU,
p1.Quantity,
p1.[Date],
SUM(p2.quantity) RunningTotal
FROM #Phistory p1
JOIN #PHistory p2
ON p1.SKU = p2.sku and p2.date >= p1.date
GROUP BY p1.SKU,
p1.Quantity,
p1.[Date]
HAVING SUM(IIF(p1.date = p2.date , 0 , p2.quantity))
<= (SELECT inv.quantity from #inventory inv where inv.sku = p1.sku)
order by p1.sku,p1.date DESC;
add a comment |
you can do it with an INNER JOIN
when summing the rows, I use IIF to set the current row to zero in the sum, because I don't want to include that in the check
begin try drop table #Phistory end try begin catch end catch;
begin try drop table #inventory end try begin catch end catch;
SELECT 1234 SKU,5 Quantity, cast('20190101' as date) [date] into #Phistory;
INSERT #Phistory (SKU, Quantity,[date]) VALUES (1234,3,'20181201'), (1234,9,'20181101'),(1234,4,'20181001'),(1234,12,'20180901'),(1235,3,'20181201'), (1235,9,'20181101'),(1235,4,'20181001'),(1235,12,'20180901'),(1235,500,'20180801'),(1235,50,'20180601');
select 1234 SKU, 10 quantity into #inventory;
insert #inventory values(1235,99);
SELECT p1.SKU,
p1.Quantity,
p1.[Date],
SUM(p2.quantity) RunningTotal
FROM #Phistory p1
JOIN #PHistory p2
ON p1.SKU = p2.sku and p2.date >= p1.date
GROUP BY p1.SKU,
p1.Quantity,
p1.[Date]
HAVING SUM(IIF(p1.date = p2.date , 0 , p2.quantity))
<= (SELECT inv.quantity from #inventory inv where inv.sku = p1.sku)
order by p1.sku,p1.date DESC;
add a comment |
you can do it with an INNER JOIN
when summing the rows, I use IIF to set the current row to zero in the sum, because I don't want to include that in the check
begin try drop table #Phistory end try begin catch end catch;
begin try drop table #inventory end try begin catch end catch;
SELECT 1234 SKU,5 Quantity, cast('20190101' as date) [date] into #Phistory;
INSERT #Phistory (SKU, Quantity,[date]) VALUES (1234,3,'20181201'), (1234,9,'20181101'),(1234,4,'20181001'),(1234,12,'20180901'),(1235,3,'20181201'), (1235,9,'20181101'),(1235,4,'20181001'),(1235,12,'20180901'),(1235,500,'20180801'),(1235,50,'20180601');
select 1234 SKU, 10 quantity into #inventory;
insert #inventory values(1235,99);
SELECT p1.SKU,
p1.Quantity,
p1.[Date],
SUM(p2.quantity) RunningTotal
FROM #Phistory p1
JOIN #PHistory p2
ON p1.SKU = p2.sku and p2.date >= p1.date
GROUP BY p1.SKU,
p1.Quantity,
p1.[Date]
HAVING SUM(IIF(p1.date = p2.date , 0 , p2.quantity))
<= (SELECT inv.quantity from #inventory inv where inv.sku = p1.sku)
order by p1.sku,p1.date DESC;
you can do it with an INNER JOIN
when summing the rows, I use IIF to set the current row to zero in the sum, because I don't want to include that in the check
begin try drop table #Phistory end try begin catch end catch;
begin try drop table #inventory end try begin catch end catch;
SELECT 1234 SKU,5 Quantity, cast('20190101' as date) [date] into #Phistory;
INSERT #Phistory (SKU, Quantity,[date]) VALUES (1234,3,'20181201'), (1234,9,'20181101'),(1234,4,'20181001'),(1234,12,'20180901'),(1235,3,'20181201'), (1235,9,'20181101'),(1235,4,'20181001'),(1235,12,'20180901'),(1235,500,'20180801'),(1235,50,'20180601');
select 1234 SKU, 10 quantity into #inventory;
insert #inventory values(1235,99);
SELECT p1.SKU,
p1.Quantity,
p1.[Date],
SUM(p2.quantity) RunningTotal
FROM #Phistory p1
JOIN #PHistory p2
ON p1.SKU = p2.sku and p2.date >= p1.date
GROUP BY p1.SKU,
p1.Quantity,
p1.[Date]
HAVING SUM(IIF(p1.date = p2.date , 0 , p2.quantity))
<= (SELECT inv.quantity from #inventory inv where inv.sku = p1.sku)
order by p1.sku,p1.date DESC;
answered Jan 18 at 17:19
CatoCato
2,807210
2,807210
add a comment |
add a comment |
I think you could probably do something like the following (untested):
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity <= i.quantity
The idea here is to calculate the running sum in the inner query, then join with your inventory table. I've made an assumption with the ORDER BY date, but you could adjust that.
Edit: So based on the comment that you want the first N rows that use all your inventory (as opposed to the first N rows that don't exceed your inventory) I think you could do something like:
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity < i.quantity
This is the same basic idea but the running sum is switched to only count previous rows (not include the current row) and the join uses < rather than <=. That way if the previous rows quantity didn't total to inventory yet, you will include the next row (even if that total now exceeds inventory).
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
add a comment |
I think you could probably do something like the following (untested):
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity <= i.quantity
The idea here is to calculate the running sum in the inner query, then join with your inventory table. I've made an assumption with the ORDER BY date, but you could adjust that.
Edit: So based on the comment that you want the first N rows that use all your inventory (as opposed to the first N rows that don't exceed your inventory) I think you could do something like:
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity < i.quantity
This is the same basic idea but the running sum is switched to only count previous rows (not include the current row) and the join uses < rather than <=. That way if the previous rows quantity didn't total to inventory yet, you will include the next row (even if that total now exceeds inventory).
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
add a comment |
I think you could probably do something like the following (untested):
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity <= i.quantity
The idea here is to calculate the running sum in the inner query, then join with your inventory table. I've made an assumption with the ORDER BY date, but you could adjust that.
Edit: So based on the comment that you want the first N rows that use all your inventory (as opposed to the first N rows that don't exceed your inventory) I think you could do something like:
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity < i.quantity
This is the same basic idea but the running sum is switched to only count previous rows (not include the current row) and the join uses < rather than <=. That way if the previous rows quantity didn't total to inventory yet, you will include the next row (even if that total now exceeds inventory).
I think you could probably do something like the following (untested):
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity <= i.quantity
The idea here is to calculate the running sum in the inner query, then join with your inventory table. I've made an assumption with the ORDER BY date, but you could adjust that.
Edit: So based on the comment that you want the first N rows that use all your inventory (as opposed to the first N rows that don't exceed your inventory) I think you could do something like:
SELECT ph.sku, ph.quantity, ph.date
FROM
(SELECT
purchasehistory.*,
SUM(quantity) OVER (PARTITION BY sku ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) as tquantity
FROM purchasehistory) ph inner join inventory i
on ph.sku = i.sku
WHERE
ph.tquantity < i.quantity
This is the same basic idea but the running sum is switched to only count previous rows (not include the current row) and the join uses < rather than <=. That way if the previous rows quantity didn't total to inventory yet, you will include the next row (even if that total now exceeds inventory).
edited Jan 18 at 19:24
answered Jan 18 at 16:43
EdmCoffEdmCoff
96936
96936
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
add a comment |
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
This got me very, very close. The SKU I'm looking at has 10 in inventory and the purchase history record I'm expecting has 12. That 12 would cover the 10 just fine. But ph.tquantity <= i.quantity is filtering it out. I'm not sure what other conditional would work there.
– BrownJenkin
Jan 18 at 18:46
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
I've added another version to the answer now that I think I understand the question better.
– EdmCoff
Jan 18 at 19:25
add a comment |
BrownJenkin is a new contributor. Be nice, and check out our Code of Conduct.
BrownJenkin is a new contributor. Be nice, and check out our Code of Conduct.
BrownJenkin is a new contributor. Be nice, and check out our Code of Conduct.
BrownJenkin is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54257848%2fquery-to-retrieve-x-number-of-rows-based-on-quantity-from-another-table%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Hi and welcome to SO. You will need a running total to solve. The solution to this varies greatly on the version of sql server you are using. Which version are you using?
– Sean Lange
Jan 18 at 16:26
I updated my question to say which version I'm using. Thanks for pointing that out!
– BrownJenkin
Jan 18 at 16:32