问题
I have table A with product_id,cost,year,quarter,... etc columns. I have another table B with product_id,base_cost,current_year,p_year,p_quarter,p_order columns.
I want to write an update query to update A from B. My conditions are -
WHERE A.product_id=B.product_id
and A.year=B.current_year
and (A.year=B.p_year and A.quarter>B.p_quarter) or A.year>B.p_year
and A.cost=0;
But the problem is, with these conditions if i have more than one rows in B then i only want to update from the row of B according to priority.
Giving logic and examples for better understanding-
basically p_ stands for priority. i want to update A's cost from B according to the p_order. Secondly, i cannot consider current and future quarters for updation.
Example 1-
If A has one row as:
product_id cost year quarter
102 0 2019 1
102 0 2019 2
102 0 2019 3
102 0 2019 4
And B has two rows corresponding to the where clause:
product_id cost current_year p_year quarter p_order
102 3.5 2019 2019 3 1
102 1.8 2019 2019 1 2
102 0.5 2019 2019 2 3
Then updated A should be:
product_id cost year quarter
102 0 2019 1
102 1.8 2019 2
102 1.8 2019 3
102 3.5 2019 4
Example 2-
If A has one row as:
product_id cost year quarter
102 0 2019 1
102 0 2019 2
102 0 2019 3
102 0 2019 4
And B has two rows corresponding to the where clause:
product_id cost current_year p_year quarter p_order
102 3.5 2019 2019 3 1
102 6.3 2019 2018 4 2
102 0.5 2019 2019 2 3
Then updated A should be:
product_id cost year quarter
102 6.3 2019 1
102 6.3 2019 2
102 6.3 2019 3
102 3.5 2019 4
回答1:
Treat this as a comment as it should. However, for some small abount of clarity I think the additional answer formatting overrides.
Your description does not match the accompanying data. In example 1 you say table A has 1 row, then proceed to show 4 rows and table B has 2 rows then proceed to show 3 rows.
Also describe in detail how your mapping occurs, taking example 2 How does (where ==> reads as Maps to)
- B(p_year,quarter,p_order) ==> A(year,quarter)
- B(2019,3,1) ==> A(2019,4)
- B(2018,4,2) ==> A(2019,1) and A(2019,2) and A(2019,3)
- B(2019,2,3) ==> none
来源:https://stackoverflow.com/questions/61253120/how-to-update-one-table-from-another-table-based-on-some-priority-that-depends-o