I have multiple tables. I only wanted to operate on these two. The objective is to project the order_id, sum of (total order cost calculated from multiple table), order_date ---grouped by each one order_id and sorted by order_date.
It sounds quite simple, but I have multiple queries, sum gave error & wrong result. I m far from getting the correct simple query for this.
Here are the tables and data :
Order_Table :
ORDERID CUSTOMERID EMPLOYEEID ORDERDATE PURCHASEORDERNUMBER SHIPDATE SHIPPINGMETHODID FREIGHTCHARGE TAXES PAYMENTRECEIVED COMMENTS
------- ---------- ---------- --------- ------------------- --------- ---------------- ------------- ----- --------------- -------------------
1 2 1 23-JAN-05 10 29-JAN-05 1 64 5 0
2 1 1 23-JAN-05 11 29-JAN-05 1 0 5 0
3 3 3 21-JAN-05 30 28-JAN-05 5 0 5 0
4 2 2 05-JAN-05 26 19-JAN-05 2 0 5 0
5 4 5 02-JAN-05 32 27-JAN-05 2 0 5 0
13 1 1 29-JAN-08 1 2 50 5 0
6 rows selected
Order_Detail_Table :
ORDERDETAILID ORDERID PRODUCTID QUANTITY UNITPRICE DISCOUNT
1 1 4 15 5 0
2 2 7 10 75 0
3 3 8 5 4 0
5 4 9 100 5 0.05
6 5 6 5 7 0
7 5 9 30 5 0.05
9 1 1 9 6 0
11 13 4 1 5 0
12 13 1 2 25 0
13 13 7 1 75 0
10 rows selected
So for example for orderid = 13. We have 3 items ordered listed on the order_detail_table.
For the unique orderid=13, I want to calculate 3 rows of (quantity*unitprice)*(1-discount). It will be 130 for orderid=13
select o.orderid, sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) as total from order_table o, order_detail_table od
where o.orderid=od.orderid group by o.orderid;
Then using those values, I would like to add the final summed values with the individual freightcharge + taxes. = (130+50)(1+tax%) = 180(1.05) = 189 for the row orderid=13.
I am stuck here, to add with the order_table.freight etc. I just met with compile and logic errors.
select o.orderid, (sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) + o.freightcharge) as total from order_table o, order_detail_table od
where o.orderid=od.orderid group by o.orderid;
Gives me SQL Error: ORA-00979: not a GROUP BY expression --- Idk why as I think the sum is only aggregate function to be grouped, while + o.freightcharge is outside of sum.
select o.orderid, sum((od.unitprice*od.quantity)*(1-od.discount*0.01)) + sum(o.freightcharge) as total from order_table o, order_detail_table od
where o.orderid=od.orderid group by o.orderid;
Gives me 3 x freightcharges, for single order in case of orderid=13. --Wrong logic.
There should be 6 rows for each unique orderid.
I tried building from several simpler queries. But I havent got success. As I think I might need to use subqueries
Pls Help.