Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Adding & Multiple Columns On Select

My database looks as follows

Table Name: Order Details

id       oid      pid   pquantity  pprice
--------------------------------------
  1       1       5        2       10
  2       1       6        3       5
  3       1       7        1       20
  5       2       8        1       5
  6       2       9        1       5
  7       3       5        5       10

Table Name: Orders

id       odiscount oshipping
----------------------------
  1       5       5        
  2       0       5        
  3       0       5  

I want to get the invoice value for each order. (pquantity*pprice)-odiscount+oshipping. The tricky part is that each order can have multiple entries in order details. So I am unable to figure out how to take care of that. The end result should be

oid   total
1     55
2     15
3     55

I tried this using the following SQL but I am unable to figure out how to take multiple rows in order details into account.

SELECT SUM((orderdetails.pprice*orderdetails.pquantity) - orders.odiscount + orders.oshipping) FROM orders LEFT JOIN orderdetails ON orderdetails.oid = orders.id GROUP BY orders.id
like image 634
Saad Bashir Avatar asked Oct 05 '16 06:10

Saad Bashir


People also ask

How do I add something in MySQL?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

What is add in MySQL?

The INSERT INTO statement is used to insert new records in a table.

How do I add a new row in MySQL?

When inserting a single row into the MySQL table, the syntax is as follows: INSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.


1 Answers

I believe you can do this without even using a subquery:

SELECT SUM(od.pquantity*od.pprice) + AVG(o.oshipping - o.odiscount)
FROM Orders o
INNER JOIN OrderDetails od
    ON o.id = od.oid
GROUP BY o.id

Demo here:

SQLFiddle

like image 105
Tim Biegeleisen Avatar answered Oct 11 '22 09:10

Tim Biegeleisen