How can i SUM records from a table to another after multiplying two columns - sql

I have a table called orderItems which has two columns, quantity and unit price.It also has a foreign key ordernumber in that very table.
I have another table called ordergroup with primary key ordernumber, which contains SavedTotal column which is the order total based on quantity * unit price for all order item rows that reference that ordernumber.
Now what i struggle with is the sql query that can get all order items based on a certain ordernumber and calculate the total cost.
I have managed to do the multiplication but i am missing the SUM, here is my sql query(based on SQL Server) so far.
UPDATE OrderGroupNew
set OrderGroupNew.SavedTotal = OrderItemNew.UnitPrice*OrderItemNew.QUANTITY
FROM OrderItemNew
inner join OrderGroupNew on OrderItemNew.OrderNumber=OrderGroupNew.OrderNumber
any help is appreciated

UPDATE OrderGroupNew
SET SavedTotal = (
SELECT SUM(UnitPrice * Quantity)
FROM OrderItemNew
WHERE OrderNumber = OrderGroupNew.OrderNumber
)

You can use a TVP as well :
;With o as (
select OrderItemNew.OrderNumber as OrderNumber,
SUM(OrderItemNew.UnitPrice*OrderItemNew.QUANTITY) as OrderSum
Group by OrderItemNew.OrderNumber)
UPDATE OrderGroupNew
set OrderGroupNew.SavedTotal = o.OrderSum
FROM o
INNER JOIN OrderGroupNew on o.OrderNumber=OrderGroupNew.OrderNumber
Well the 1st answer is correct too. Choose the best in term of performance :) (dont know which will be the best, to be honest ! )

Related

sql can't check column1>column2 not working

I have some problem in sql syntax.
i have products table and below two column
total_quantity (Its total quantity for products)
remain_alert_quantity
i want to get records that are below remain_alert_quantity
select * from products where total_quantity<remain_alert_quantity
but its not work .
can i check condition with column value in sql.
thanks and regards.
Given data is not sufficient so I am assuming few thing like,
you want to compare the product quantity with the remain_alert_quantity of same product.
There is some unique column in table (like product_id)
in this case try the below query.
select * from products a where a.total_quantity<
(select b.remain_alert_quantity from products b where b.product_id=a.product_id);

Oracle SQL return sum of multiple across tables

Farily new to SQL and the IT world, and always do a lot of work before asking for help but this time I am stumped.
I have three tables:
So I am trying to update the "payment_owed" table by doing the following:
For each customer, get the food_id and quantity, then using the food_id multiply the quantity by the cost.
The best I have done this far is a natural join on the tables, and attempting to sum the quantity * cost for each ID
My understanding for updating a specific customer:
update customer
set payment_owed = (select <quantity>) * (select <cost>)
where cust_no = 1;
If im not on the right forum or there's a better place to ask these questions let me know, thank you for your time!
Simply:
update customer
set payment_owed = (SELECT SUM(o.cost*s.quantity)
FROM order o JOIN session s ON s.food_id = o.food_id
WHERE s.cust_no = customer.cust_no)
where cust_no = 1;
Anyway will you update it after every change on table? How about using view like:
CREATE VIEW my_view AS
SELECT cust_no, SUM(o.cost*s.quantity)
FROM order o
JOIN session s ON s.food_id = o.food_id
GROUP BY cust_no;

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?

simple SQL update query error that i have no idea how to solve

I have two tables:
PS(size(primary key), price)
Sales(....size,quantity, total_Price)
I tried to execute this statement:
update Sales
set total_Price = (select price from PS, Sales
where Sales.size = PS.size )*Quantity;
but i get this error always
SQL0811N The result of a scalar fullselect, SELECT INTO statement, or
VALUES INTO statement is more than one row.
I know that the error is because the sub query i used in the select statement returns more than one row, that's why i can't work. Can someone please help me solve this problem.
ASSUMING size in PS is UNIQUE
update Sales
set total_Price = (SELECT max(PS.price) FROM PS PS
INNER JOIN Sales S on S.Size = PS.Size)*Quantity;
The problem I think is that your sales table contains multiple entries per size. Thus it's duplicate the price in the PS table. You either need the max price from that table, or the distinct value ASSUMING size is a unique value in the PS table. If size is NOT unique in the PS table then I would need to rethink what you're trying to do.

Update using a subquery with aggregates and groupby in Postgres

I'm trying to update a column in a table with the max value of that column grouped by another column.
So for example, say we have a table named transactions with two columns: quantity and item_name. And for whatever reason we want to set quantity equal to the maximum quantity found for each item_name.
I'm pretty stumped and bad at doing things like this in SQL, but here's what I have so far:
UPDATE transactions
SET
quantity = subquery.quantity
FROM (select max(quantity), item_name
from transaction group by item_name) AS subquery
WHERE and item_name = subquery.item_name;
In addition to your syntax errors that #Gordon already pointed out, it is regularly a good idea to exclude empty updates:
UPDATE transaction t
SET quantity = sub.max_quantity
FROM (
SELECT item_name, max(quantity) AS max_quantity
FROM transaction
GROUP BY 1
) sub
WHERE t.item_name = sub.item_name
AND t.quantity IS DISTINCT FROM sub.max_quantity;
No need to write new row versions (at almost full cost) without changing anything. (Except if you want to fire a trigger.)
You are actually quite close:
UPDATE transactions
SET quantity = subquery.quantity
FROM (select max(quantity) as quantity, item_name
from transactions
group by item_name
) subquery
WHERE transactions.item_name = subquery.item_name;
I just removed the and in where and and renamed the table in the subquery to transactions.
Try this, it should also work for you. It would evaluate the quantity for each and every row and may be slower than Gordon's answer.
UPDATE transactions
SET quantity = (SELECT MAX(quantity)
FROM transaction as t
WHERE t.item_name = transactions.item_name)