I’m trying to come up with a query that will pull the total quantity of an item from its first ever order. I understand how to pull out each item and their first order number was, but I’m trying to see each items first order, and the total amount of that item on that specific order. The item can have multiple lines on the same order which seems to be throwing me off. Here is an example table
Item | Order# | Quantity |
---|---|---|
A | 1 | 10 |
A | 1 | 15 |
A | 2 | 5 |
A | 2 | 5 |
B | 3 | 50 |
I want the results to be like this where it just takes the items first order ( min() ) and sums the QTYs of the lines for that item on that order only:
Item | Order# | Quantity |
---|---|---|
A | 1 | 25 |
B | 3 | 50 |
I did something simple like this:
SELECT
item,
min(order),
sum(quantity)
FROM orders
GROUP BY item
It will show me the min order of course, but how do I get the sum to only sum the quantity of that specific item on that specific first order? Currently when I run it shows the first order with the item, but it sums the qty across all orders for the item and I’m having trouble. Any help would be appreciated. Thanks!
2
Answers
Join the table with a subquery that gets the first order number for each item.
DEMO
order
is a reserved word, so it’s best to avoid using it as a column name.One option is to use correlated subquery in the WHERE clause …
… OR in the HAVING Clause …
R e s u l t : ( same for both )
fiddle