Update table based on a select from another - sql

I have this select statement below which I would like to use to update the quantity of the products in another table, tablex. I cannot seem to figure out how to match the product number from this query to the productnumber tablex and then add the quantity found in this statement to the existing quantity in tablex.
select
p.ProductNumber, sod.Quantity ,so.StateCode
from
SalesOrderDetail sod
right join
ProductAssociation pa on sod.ProductId = pa.ProductId
left join
Product p on pa.AssociatedProduct = p.ProductId
left join
SalesOrder so on so.SalesOrderId = sod.SalesOrderId
where
so.StateCode = '3'

You can have update base on multiple tables, the syntax is something like
update tablex
set tablex.quantity = sod.Quantity
from tablex join product p on tablex.productnumber = p.ProductNumber
join... -- add the rest of your joins and conditions.

I'm guessing that you're trying to update a large quantity of rows in TableX so I'm going to suggest a way to do them all at once rather than one at a time.
update TableX
set quantity = quantity +
(select sod.quantity from SalesOrderDetail where sod.ProductId = TableX.ProductId)
You might wish to do this on a subset of SalesOrderDetail, and that's fine, just use the WHERE clause for that.

Try
UPDATE tablex
SET Quantity= Quantity +
(SELECT sod.Quantity FROM SalesOrderDetail sod
RIGHT JOIN ProductAssociation pa ON sod.ProductId=pa.ProductId
LEFT JOIN Product p ON pa.AssociatedProduct=p.ProductId
LEFT JOIN SalesOrder so ON so.SalesOrderId=sod.SalesOrderId
WHERE so.StateCode='3' AND p.ProductNumber=Tablex.productnumber)

Are you looking for this?
UPDATE tx SET tx.Quantity = tx.Quantity + sod.Quantity FROM
from SalesOrderDetail sod
right join ProductAssociation pa on sod.ProductId=pa.ProductId
left join Product p on pa.AssociatedProduct=p.ProductId
left join SalesOrder so on so.SalesOrderId=sod.SalesOrderId
left join tablex tx on p.ProductNumer = tx.ProductNumber
where so.StateCode='3'
How can I do an UPDATE statement with JOIN in SQL?

Basic syntax for UPDATE with a JOIN:
UPDATE A
SET A.foo = B.bar
FROM TableA A
JOIN TableB B
ON A.col1 = B.colx
So I believe you're after something like:
UPDATE A
SET A.Quantity = B.Quantity + A.Quantity
FROM Tablex A
JOIN (select p.ProductNumber, sod.Quantity ,so.StateCode
from SalesOrderDetail sod
right join ProductAssociation pa on sod.ProductId=pa.ProductId
left join Product p on pa.AssociatedProduct=p.ProductId
left join SalesOrder so on so.SalesOrderId=sod.SalesOrderId
where so.StateCode='3'
)B
ON A.ProductNumber = B.ProductNumber
Not sure how your StateCode factors in, additional JOIN criteria perhaps?

Related

Update based on the results of previous update statement

We had a requirement to update price values in the Orders table based on the productids from the Products table. This is simple:
update o
set o.price = p.price
from Orders o
inner join Products p
on o.productid = p.productid
Then the ask was to update the price from a different table (OrderPricing) based on a different column (orderpricingid) for the orders that were not updated by the previous query.
So I have another update statement:
update o
set o.price = op.price
from Orders o
inner join OrderPricing op
on o.orderpricingid = p.orderpricingid
where o.price is null
So my question is - can the two update statements be combined together? Is there a way to update based on the results of the previous update query?
You can do both in the same query, if you change the joins from inner to left, using coalesce:
update o
set o.price = coalesce(p.price, op.price, o.price)
from Orders o
left join Products p on o.productid = p.productid
left join OrderPricing op on o.orderpricingid = p.orderpricingid
This will update the price from the products table if the product exists there, if not, it will use the price from the OrderPricing table, but if that also don't exists it will just keep the original price.
You can try this way, as if o.price is null then you will update from order price so we can use case when in time of update
update o
set o.price= case when p.price is null then op.price else p.price end
from Orders o
inner join Products p
on o.productid = p.productid
inner join OrderPricing op
on o.orderpricingid = p.orderpricingid
I believe you need a left join:
update o
set o.price = coalesce(p.price, op.price)
from Orders o left join
Products p
on o.productid = p.productid left join
OrderPricing op
on o.orderpricingid = p.orderpricingid;

Update SQL Query with where condition

I added a column in the Orders table called EventId and I have to fill the column with the right value for every row.
I want to achieve it with a more complex sql query like below:
UPDATE [dbo].[Orders] o
SET o.EventId = ????
WHERE o.Id IN (SELECT o.id, s.eventid FROM orders o
INNER JOIN orderskudiscounts osd ON o.id = osd.orderid
INNER JOIN skus s ON osd.skuid = s.id GROUP BY o.id, s.eventid)
I not sure how can I write the query successfully... I have more than 2 thousand mapping to do. So I should use a query...
Thank for any help
I am guessing that you want an update like this:
UPDATE o
SET o.EventId = s.eventid
FROM orders o INNER JOIN
orderskudiscounts osd
ON o.id = osd.orderid INNER JOIN
skus s
ON osd.skuid = s.id;

SQL query show all IDs regardless if present or not

I have a very basic SQL question. There are two tables: products and inventory. If I search on the products ID in the inventory table (using a left join shown below) I get all the product IDs (names) which have quantity in the inventory. But I would like to have shown all the product IDs and if they are not present in the inventory then have a 0 or Null as quantity.
Right now my code only shows the IDs which have quantity in the inventory table
Select A.ProductID, A.Name, B.Quantity
From Production.Product A
Left join Production.ProductInventory B
On A.ProductID = B.ProductID
Where B.LocationID = 1
Thank you for your help in advance!
You have to move predicate
B.LocationID = 1
from WHERE clause to ON:
Left join Production.ProductInventory B
On A.ProductID = B.ProductID AND B.LocationID = 1
If the predicate is in WHERE then LEFT JOIN becomes an INNER JOIN, since for NULL records the predicate will not evaluate to TRUE.
So, your query will be:
Select A.ProductID, A.Name, B.Quantity
From Production.Product A
Left join Production.ProductInventory B
On A.ProductID = B.ProductID AND B.LocationID = 1
This returns all Production.Product records. Field Quantity of Production.ProductInventory is returned by the query only when ProductID fields match and LocationID = 1, otherwise NULL is returned.

SQL Query or Table Error?

So Im trying to find the total amount spent on Cuts and Products by each Customer
I don't know if my Query is Wrong or my entire Database Schema any ideas?
My Query
`Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A, cuts B, products C, customers D
Where A.Customer_ID= D.Customer_ID
AND A.Cut_ID = B.Cut_ID
AND A.Product_ID= C.Product_ID;`
My Database
`Table: bookings
Booking_N0, Customer_ID, Cut_ID, Product_ID, TimeTaken`
`Table: customers
Customre_ID, First_Name, Sex`
`Table: products
Product_ID, Products, Cost`
`Table: cuts
Cut_ID, Cut, Cost`
You should GROUP BY to SUM by each customer :
Select D.First_Name
, SUM(B.Cost)
, SUM(C.Cost)
FROM bookings A LEFT JOIN cuts B ON A.Cut_ID = B.Cut_ID
JOIN products C ON A.Product_ID = C.Product_ID
JOIN customers D ON A.Customer_ID = D.Customer_ID
GROUP BY D.First_Name;
Also, look forward using explicit join notation (FROM table1 t1 JOIN table2 t2 ON t1.field1 = t2.field2) instead of implicit join notation (FROM table1 t1, table2 t2 WHERE t1.field1 = t2.field2), because it is has more intuitive view (tables are listed near conditions on which they are joined).
Start using recommended JOIN / ON syntax for joining instead of using WHERE clause . You also need a GROUP BY clause
Select First_Name, SUM(B.Cost), SUM(C.Cost)
FROM bookings A
INNER JOIN cuts B
ON A.Cut_ID = B.Cut_ID
INNER JOIN products C
ON A.Product_ID= C.Product_ID
INNER JOIN customers D
ON A.Customer_ID= D.Customer_ID
GROUP BY First_Name
If you use aggregate function like SUM you have to add a group by clause
in your case:
...
AND A.Product_ID= C.Product_ID
GROUP BY First_Name

sql - How can I extract all information through one statement from 3 tables?

I have 3 tables.
First one:
Stores(StoreID, Name)
Second one:
Store_Items(StoreID, ItemID)
Third one:
Items(ItemID, Name, Price)
How can I write a single statement, which get all StoreID and all names and all items for each StoreID?
Should I use Join or something?
select *
from Store as S
left outer join Store_Items as SI on SI.StoreID = S.StoreID
left outer join Items as I on I.ItemID = SI.ItemID
select s.storeid, s.name, si.itemid, i.name, i.price
from store s
left join store_item si on si.storeid = s.storeid
left join item i on i.itemid = store.itemid
Yes, you should join the tables roughly as such
SELECT * FROM `firstone`
LEFT OUTER JOIN `secondone`
ON firstone.StoreId = secondone.StoreID
LEFT OUTER JOIN `thirdone`
ON secondone.ItemID = thirdone.ItemID