Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (MySQL) multiply columns and then the sum rows?

Tags:

mysql

I've got this table:

id    |   payment_id   | quantity  |  unit cost
1           633             1            750  
2           633             1            750 
3           632             2            750 
4           632             2            750 

What I need is :

payemnt_id  |   total
    633           1500
    632           3000 

You can also think of this as Countries and then you are trying to find the total for each Country. I was sure there were some tutorials like this but could not find by STFW.

like image 234
trafalgar Avatar asked Jul 23 '13 09:07

trafalgar


People also ask

How do you multiply columns in MySQL?

All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .

How do you write a multiplication in SQL?

The SQL multiply ( * ) operator is used to multiply two or more expressions or numbers.


1 Answers

You can simply put the formula (expression) inside SUM:

SELECT payment_id, SUM(`unit cost` * quantity) AS total
FROM myTable
GROUP BY payment_id
like image 68
lc. Avatar answered Nov 06 '22 01:11

lc.