mysql> select * from orders;
+---------+------------+------------+------------+----------+----------+
| orderid | customerid | orderdate | shipdate | shipping | salestax |
+---------+------------+------------+------------+----------+----------+
| 1 | 1 | 2008-03-31 | 2008-03-31 | 4.99 | 5.00 |
| 2 | 1 | 2008-04-01 | 2008-04-02 | 5.99 | 5.00 |
| 3 | 2 | 2008-04-01 | 2008-04-02 | 3.99 | 6.00 |
| 4 | 3 | 2008-04-02 | 2008-04-02 | 6.99 | 7.50 |
+---------+------------+------------+------------+----------+----------+
4 rows in set (0.02 sec)
mysql> select * from orderinfo;
+---------+------------+-----+-------+----------+
| orderid | isbn | qty | price | detailid |
+---------+------------+-----+-------+----------+
| 1 | 0929306279 | 1 | 29.95 | 1 |
| 1 | 0929306260 | 1 | 49.95 | 2 |
| 2 | 0439357624 | 3 | 16.95 | 3 |
| 3 | 0670031844 | 1 | 34.95 | 4 |
| 4 | 0929306279 | 1 | 29.95 | 5 |
| 4 | 0929306260 | 1 | 49.95 | 6 |
| 4 | 0439357624 | 1 | 16.95 | 7 |
| 4 | 0670031844 | 1 | 34.95 | 8 |
+---------+------------+-----+-------+----------+
8 rows in set (0.00 sec)
im trying to multiply the qty and price from the orderinfo table then add the shipping from the order table when i try to multiple them it works fine but when I add the shipping I get an incorrect value
this works
mysql> select orders.orderid,sum(orderinfo.qty*orderinfo.price) as order_total from orders
-> inner join orderinfo
-> on orders.orderid=orderinfo.orderid
-> group by orderid;
+---------+-------------+
| orderid | order_total |
+---------+-------------+
| 1 | 79.90 |
| 2 | 50.85 |
| 3 | 34.95 |
| 4 | 131.80 |
+---------+-------------+
4 rows in set (0.00 sec)
this gives an incorrect value
mysql> select orders.orderid,sum(orderinfo.qty*orderinfo.price+orders.shipping) as order_total from orders
-> inner join orderinfo
-> on orders.orderid=orderinfo.orderid
-> group by orderid;
+---------+-------------+
| orderid | order_total |
+---------+-------------+
| 1 | 89.88 |
| 2 | 56.84 |
| 3 | 38.94 |
| 4 | 159.76 |
+---------+-------------+
4 rows in set (0.00 sec)
You are applying the
shippingrate inside theSUM()aggregate, when really you need to add it afterward, to the result of theSUM(). This has the effect of adding theshippingvalue for each row of the aggregated group, that is, double shipping fororderid = 1and 4x shipping fororderid = 4.You can do this by adding
shippingto theGROUP BY(actually MySQL doesn’t require this, but it is good practice).Here’s an example on SQLFiddle.com.