简体   繁体   中英

Function SUM is not working as expected in MYSQL

I have 2 tables

table_orders - order_id, customer_id;
table_order_details - order_id, product_sell_price, quantity;

I want to get the order-value(sum of amount) for each of the orders. I am trying this query:

mysql> select O.order_id, sum(OD.product_sell_price * OD.quantity) from table_order_details as OD INNER JOIN table_orders as O where O.order_id = TOD.order_id;

But it is giving overall sum ie sum for all the orders.

How to get the order-value for each order?

Can anybody help me on this?

Add at the end a GROUP BY

SELECT O.order_id, SUM(OD.product_sell_price * OD.quantity) 
FROM table_order_details as OD 
INNER JOIN table_orders as O 
ON O.order_id = OD.order_id
 GROUP BY  O.order_id

You just have to use GROUP BY clause to fetch orderwise SUM

Try this:

SELECT O.order_id, SUM(OD.product_sell_price * OD.quantity) 
FROM table_order_details AS OD 
INNER JOIN table_orders AS O WHERE O.order_id = OD.order_id
GROUP BY O.order_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM