SQL-Oracle: Updating table column with sum of values from another table - using common key column/s criteria - sql

Good Evening Stackoverflow team/members
Oracle version: 11g Release 11.1.0.6.0 - 64bit Production
I have two Tables: ORDERS and ITEMS.
ORDERS looks like this
ORDERS
ITEMS looks like this
enter image description here
Table ORDERS has 1 or more Order_Number each assigned to at least one depot or more. the column Total_Value SHOULD store exactly the sum of the item values associated to an order number. the table ITEMS in fact stores via parcel_code items values for a specific order_number/s.
my db has a bug for orders that have more than one depot assigned to an order number (e.g. order number 1 and 4) do not store the actual total value correctly.
in my case I cannot figure out the UPDATE statement that would select order numbers that would take the sum from the table ITEMS and link it via parcel_code and update the column total_value in the table ORDERS.
the result of my update should give this back:
for table orders i should get back for
order number 1:
for both rows total value 1120
order number 4
for both rows total value: 350
order number 2 and 3 as they are single depot order remain the same:
50 and 20
pseudo-code :
update ORDERS
set total_value = (select sum(I.item_value) from ITEMS I, ORDERS O where O.parcel_code = I.parcel_code)
i would update also those orders which have on e depot assigned as they will exactly the same.
i was looking at MERGE statements or INNER select queries. the problem i am facing is that my update must be dynamic. this means not driven by values but by columns joins as i may have to create a process that update this every day.
can someone help me?

You need to join the items and orders tables together, then select the sum of all item_values where your order_number is equal to the row which you are updating (in table o1).
update
Orders o1
set o1.total_value = (
select sum(i.item_value) from Items i
join Orders o2 on o2.parcel_code = i.parcel_code
where o2.Order_number = o1.Order_number
)

Related

Left Join misbehaving - VBA SQL

Table 1: Customer Info Data (has ~50K records)
Table 2: Sales by customer ID (has ~25K records)
When I am performing a left join of Sales data from Table 2 on Table 1 based on the Customer ID, the output has a handful of records (~500) with a unit increase in the sales quantity. For e.g. sales quantity for customer #1 is 200, the sale quantity that I am getting in my joined output is 201. Note again that this is only for handful of records, for the majority of the data, it is joined absolutely correctly.
The SQL query is a pretty standard one:
SELECT [Table1$].[ID], Name, Volume, Amount
FROM [Table1$] LEFT JOIN [Table2$] ON [Table1$].[ID] = [Table2$].[ID]
What is weird is that this error is only for a few records and it is changing only by a unit for all of them. What do you think could be the potential reason here? Note that I run this SQL query from VBA.
Edit:
Maybe if I add an image, it would help, I have masked my data:
Table1, blue colored column is the joined column, I have filtered for the ID where there is a problem:
Table2, source of the joined column, as you can see it is 20, but the value that has been joined with table 1 is 21. Interestingly, there is no ID with value 21 in table2
There is certainly a space or something that makes seemingly identical IDs different. To make sure do a select distinct id on the sales table.

Oracle SQL Update a column based on another table but based on a date

Learning SQL so please forgive me.
I have a table that holds many accounts(and sub accounts) and another table that holds many orders they are custom tables taken from different databases.
What I am trying to do is update order_amt on the account table with the order_val value from the orders table but if there are more than one order with that account I want the order amount from the earliest order date only.
Account Table
Acc _Num..........Comp_Name.......Order_Amt.......Int_Id
123456789-1.....ABC Ltd.......................................123456789
123456789-2.....ABC Ltd.......................................123456789
987654321-1.....Xyz Ltd.........................................987654321
987654321-2.....Xyz Ltd.........................................987654321
Orders Table
Order_Num.....Order_Dt.....Order_Val.....Acc_num
1......................01/01/13......£20.00...........123456789
2......................01/01/14......£10.00...........123456789
3......................01/01/10......£100.00..........987654321
4......................01/01/11......£200.00..........987654321
So the order_amt for accounts 123456789-1 & 2 = £20.00 and from 987654321-1 & 2 would be £100.00.
UPDATE accounts a
SET a.order_amt =
(
SELECT order_val
FROM orders o
WHERE a.int_id = o.acc_num
AND EXISTS
(
SELECT MIN(order_dt)
FROM orders oa
WHERE o.order_num = oa.order_num
);
I am getting a few errors including the error that more than one row returned? Could anyone please help me?
kind Regards
Eden
I think you need something like this:
UPDATE accounts a
SET a.order_amt =
(
SELECT order_val
FROM orders o
WHERE a.int_id = o.acc_num
GROUP BY order_val
HAVING order_dt = MIN(order_dt);
);
Create a FK on the column account_number inside of the orders table and have it reference the auto-increment account id of the accounts table.
Then as Roger suggest, with the slight modification of the column int_id AND a modification of the HAVING clause
UPDATE accounts a
SET a.order_amount =
(
SELECT order_value
FROM orders o
WHERE a.account_number = o.account_number
GROUP BY order_value
HAVING MIN(order_date)
)
This will not fix the error that is occurring with more than one row being returned though since there are multiple orders with the same account id attached to them. You will need to be more specific about how what you are needing. Do you want the average of all order amounts to equal the order value in the accounts table? Or maybe the MAX/MIN value?

Joining table issue with SQL Server 2008

I am using the following query to obtain some sales figures. The problem is that it is returning the wrong data.
I am joining together three tables tbl_orders tbl_orderitems tbl_payment. The tbl_orders table holds summary information, the tbl_orderitems holds the items ordered and the tbl_payment table holds payment information regarding the order. Multiple payments can be placed against each order.
I am trying to get the sum of the items sum(mon_orditems_pprice), and also the amount of items sold count(uid_orderitems).
When I run the following query against a specific order number, which I know has 1 order item. It returns a count of 2 and the sum of two items.
Item ProdTotal ProdCount
Westvale Climbing Frame 1198 2
This order has two payment records held in the tbl_payment table, which is causing the double count. If I remove the payment table join it reports the correct figures, or if I select an order which has a single payment it works as well. Am I missing something, I am tired!!??
SELECT
txt_orditems_pname,
SUM(mon_orditems_pprice) AS prodTotal,
COUNT(uid_orderitems) AS prodCount
FROM dbo.tbl_orders
INNER JOIN dbo.tbl_orderitems ON (dbo.tbl_orders.uid_orders = dbo.tbl_orderitems.uid_orditems_orderid)
INNER JOIN dbo.tbl_payment ON (dbo.tbl_orders.uid_orders = dbo.tbl_payment.uid_pay_orderid)
WHERE
uid_orditems_orderid = 61571
GROUP BY
dbo.tbl_orderitems.txt_orditems_pname
ORDER BY
dbo.tbl_orderitems.txt_orditems_pname
Any suggestions?
Thank you.
Drill down Table columns
dbo.tbl_payment.bit_pay_paid (1/0) Has this payment been paid, yes no
dbo.tbl_orders.bit_order_archive (1/0) Is this order archived, yes no
dbo.tbl_orders.uid_order_webid (integer) Web Shop's ID
dbo.tbl_orders.bit_order_preorder (1/0) Is this a pre-order, yes no
YEAR(dbo.tbl_orders.dte_order_stamp) (2012) Sales year
dbo.tbl_orders.txt_order_status (varchar) Is the order dispatched, awaiting delivery
dbo.tbl_orderitems.uid_orditems_pcatid (integer) Product category ID
It's a normal behavior, if you remove grouping clause you'll see that there really are 2 rows after joining and they both have 599 as a mon_orditems_pprice hence the SUM is correct. When there is a multiple match in any joined table the entire output row becomes multiple and the data that is being summed (or counted or aggregated in any other way) also gets summed multiple times. Try this:
SELECT txt_orditems_pname,
SUM(mon_orditems_pprice) AS prodTotal,
COUNT(uid_orderitems) AS prodCount
FROM dbo.tbl_orders
INNER JOIN dbo.tbl_orderitems ON (dbo.tbl_orders.uid_orders = dbo.tbl_orderitems.uid_orditems_orderid)
INNER JOIN
(
SELECT x.uid_pay_orderid
FROM dbo.tbl_payment x
GROUP BY x.uid_pay_orderid
) AS payments ON (dbo.tbl_orders.uid_orders = payments.uid_pay_orderid)
WHERE
uid_orditems_orderid = 61571
GROUP BY
dbo.tbl_orderitems.txt_orditems_pname
ORDER BY
dbo.tbl_orderitems.txt_orditems_pname
I don't know what data from tbl_payment you are using, are any of the columns from the SELECT list actually from tbl_payment? Why is tbl_payment being joined?

How can I apply the LIMIT statement in a SQLite query to a specific side of a join?

Here's my requirement:
I have 2 tables, orders and orderContents. For each row in the orders table, there are a certain number of rows that contain description of the order. id column serves as foreign key.
What I want is to get all the details for each order (details from orderContents, including id column from orders table) table, but limit no. of results based on common column (foreign key, id)
Problem is that it limits orderContents rows, instead of limiting order rows.
How can I achieve desired effect?
EDIT: Updating tables and desired result set
Orders table:
OrderContents table:
Desired result on limiting number of records to 2:
I'm assuming you are trying to say that you want the results from both tables but only for the first X orders. If so, try this:
SELECT OC.*, O.* FROM OrderContents OC
INNER JOIN (SELECT *
FROM Orders
ORDER BY ID
LIMIT 2) O ON O.ID=OC.ID

SQL table update from selection/join with multiple columns, only one column data needed

Firstly, I'm rather new to SQL and I've run into a roadblock. I'm using the Mimer SQL system.
I have three tables: "Transactions", roughly equivalent with a receipt total, which I want to update with data from a selection and the tables "item", containing prices and "sale", containing number of items and item IDs for a given transaction, which I have to join in order to get the data to update Transaction with.
SELECT sale.T_ID, SUM(sale.quantity * item.price) as total
FROM sale
INNER JOIN item
ON sale.I_ID = item.I_ID
GROUP BY T_ID
Gives me the desired data selection with the transaction IDs and the sum total for that transaction:
T_ID Amount
1 100
2 150
etc...
I want to update the Transaction table, which contains columns "T_ID" and "Total". I want to match the T_IDs and update the Total with the data from the corresponding Amount in the selection. The query:
UPDATE transaction SET total = (
SELECT total FROM (
SELECT sale.T_ID, SUM(sale.quantity * item.price) as total
FROM sale
INNER JOIN item
ON sale.I_ID = item.I_ID
GROUP BY T_ID)
WHERE transaction.T_ID=T_ID);
I can sense that the above statement is faulty, but unable to discern the problem. How should I construct the query?
Only select the SUM(sale.quantity * item.price) in your subquery and remove the select total one.
update Transaction
set total = (
select SUM(sale.quantity * Item.price)
from Sale
inner join Item on Sale.I_ID = Item.I_ID
where Sale.T_ID = Transaction.T_ID
)
That is what I would try out in SQL Server.
I would have prefered to have some sample data so that I can test it against my local SQL Server database in order to verify whether this statement does what is expected, though you're not using SQL Server, the idea is still the same.
EDIT #1
Though I do not fully understand why it does not overwrite values in the transaction.total column when a transaction is composed of several different items, your suggested query works.
The behaviour of the SUM function is to sum all targeted records resulting in only one scalar value for each Sale and Item rows. There can be only one sum, can it not?
That said, it multipies each resulting rows from the constraint, that is, for a particular transaction.
It selects both Sale and Item rows for this very transaction;
It then iterates through each of the resulting rows and multiply Sale.Quantity and Item.Price together, which is worth a value for each row;
Once a row is multiplied, its total is then added to a total which is stored somewhere in memory;
Once it has processed all the rows for that transaction, it comes out with a scalar value, which is the sum of all the rows in Sale and Item for that given transaction;
This SUM ends up to be this transaction's total.
In other words, the subquery "knows" for which transaction to sum which is filtered in the subquery itself. The Transaction table is accessible in the subquery as part of the main SQL statement. So, putting it in the where clause filters the rows from Sale and Item that will be later multiplied and additioned for the total.
Does this help you better understand this update statement?
Please feel free to ask your questions. =)