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 theselect totalone.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
The behaviour of the
SUMfunction is to sum all targeted records resulting in only one scalar value for eachSaleandItemrows. 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.
SaleandItemrows for this very transaction;Sale.QuantityandItem.Pricetogether, which is worth a value for each row;SaleandItemfor that given transaction;In other words, the subquery “knows” for which transaction to sum which is filtered in the subquery itself. The
Transactiontable is accessible in the subquery as part of the main SQL statement. So, putting it in thewhereclause filters the rows fromSaleandItemthat 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. =)