I have 3 tables.
Table Product
Product_ID | Review_date |
1 | 01/01/2018 |
2 | 01/01/2018 |
3 | 01/01/2018 |
4 | 01/01/2018 |
Table Inventory
Inventory_ID | Product_ID | Location_ID
1 | 2 | 1 |
2 | 2 | 3 |
3 | 3 | 4 |
4 | 1 | 4 |
Table Location
Location_ID| Review_date |
1 | 04/02/2018 |
2 | 06/03/2018 |
3 | 01/05/2018 |
4 | 08/28/2018 |
UPDATE The product table set of product information. The inventory table has information about places where the products are available, One product can have multiple inventories and a product can have no inventories. The location table has unique list of all the possible locations. The review date in the location table is often updated.
I want to update the review date in the product table for each product ID and selecting the max(review_date) from location table for each product ID. Because a product can have multiple inventories and locations assigned to it. I want the recent date the product's location is updated.
Expected result
Table Product
Product_ID | Review_date |
1 | 08/28/2018 | this prod id in inventory has loc id 4.
2 | 04/02/2018 | two inv records for the product so max date
3 | 08/28/2018 |
4 | 01/01/2018 | no inv record. so leave it as such
UPDATE P
SET P.review_date = L.Inventory_review_date
FROM Product AS P
CROSS APPLY
(
select top 1 inventory_review_Date
from Location as L, Inventory as I, PRODUCT as P
where L.Location_ID = I.Inventory_ID and P.Product_ID = I.Product_ID
order by
L.Inventory_Review_date desc
) as L
I tried something like this in different ways but i dont seem to get it. Any help appreciated. TIA
It looks like you're joining the location table to the inventory table on two different pieces of informaiton. (location id and product id) If LocationID in the Inventory table is a location ID and not a date (as in your example), try this. (Not tested)
UPDATE P
SET P.review_date = L.Inventory_review_date
FROM Product AS P
CROSS APPLY
(
select top 1 inventory_review_Date
from Location as L, Inventory as I, PRODUCT as P
where L.Location_ID = I.Location_ID and P.Product_ID = I.Product_ID
order by
L.Inventory_Review_date desc
) as L
Also, I would think that you are going to have to order by Location_ID to get all locations together, then choose the top date. I haven't tried it, so the aggregate function of TOP might not let you do this.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments