1
mysql> select * from fact_lab;
    +---------+--------+-----+
    | product | amount | box |
    +---------+--------+-----+
    | a       |    100 |   1 |
    | b       |    200 |   1 |
    | c       |     50 |   1 |
    | a       |    200 |   2 |
    | b       |    100 |   2 |
    | c       |     50 |   2 |
    | a       |    100 |   3 |
    | b       |    200 |   3 |
    | c       |     50 |   3 |
    +---------+--------+-----+
    9 rows in set (0.00 sec)

I am looking for an output where I can see the total sum of amounts for each product that will show a comparison with amounts for box 2. So, the output should be like the below

+---------+--------+-----+
| product | amount | inbox2 |
+---------+--------+-----+
| a       |    400 | 200 |
| b       |    500 | 100 |
| c       |    150 |  50 |
+---------+--------+-----+

How can i get this result in a single query?

1 Answer 1

4

You can get what you want with aggregation. The group by is a basic part of the SQL language. If you don't understand it, then you should study up a bit more on the language.

The second part uses condition aggregation. That is, a case statement is the argument to sum():

select fl.product, sum(amount) as amount,
       sum(case when box = 2 then amount else 0 end) as inbox2
from fact_lab fl
group by fl.product;
Sign up to request clarification or add additional context in comments.

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.