1

I have a simple question but I can't find an answer (please give me a link if that question is on stackoverflow forum). Table has orderid and quantity columns. How to select orderid, quantity, total_in_order, where total_in_order is a sum of quantity for current orderid So the table looks the same, but with additional column. Example:

orderid - quantity - **total_in_order**
 1      -  43      - **78**
 1      -  24      - **78**
 1      -  11      - **78**
 2      -  31      - **31**
 3      -   9      - **25**
 3      -  16      - **25**

So, how to modify SELECT orderid, quantity, SUM(quantity) from orders; ? Thank you.

0

3 Answers 3

3

Use a join to a subselect. In the subselect calculate the totals for each orderid.

SELECT
    orders.orderid,
    orders.quantity,
    totals.total_in_order
FROM orders
JOIN
(
    SELECT orderid, SUM(quantity) AS total_in_order
    FROM orders
    GROUP BY orderid
) AS totals
ON orders.orderid = totals.orderid
Sign up to request clarification or add additional context in comments.

1 Comment

Looks like I gave the exact same answer you did. Sorry I didn't see yours before I posted mine.
1

First approach:

SELECT 
   O.orderid, 
   O.quantity, 
   ( select sum( O2.quantity) 
     from orders O2
     where O.orderid = O2.orderid ) as qty
from 
   orders O

1 Comment

I believe this would make a sub select for each row in orders, you should check out @Marks answer.
0

Here is an example on how to do it using a subquery. It should do the job.

SELECT A.orderid
   A.quantity
   B.sum
FROM 
   orders A JOIN ( SELECT orderid, sum(quantity) as sum from orders group by orderid) as B on(A.orderid=B.orderid)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.