I have 2 tables as following:
Table 1:
ID_M, Date, Reservation
001, 2014, 5
001, 2015, 10
001, 2016, 18
002, 2015, 6
002, 2016, 22
Table 2:
ID_M, ID_type, Priority,Product_Total
001, 1111, 2, 10
001, 2222, 3, 15
001, 3333, 1, 8
002, 1111, 2, 12
002, 2222, 1, 16
Is it possible to calculate the repartition ID_TYPE for reservation? Table 2 priority indicate the order for the reservation, priority 1 is to reserve first and etc. Is it possible to create a table/View/CTE in T-SQL like following?
ID_M, ID_Type, DATE, Reservation
001, 3333, 2014, 5,
001, 3333, 2015, 3,
001, 1111, 2015, 7,
001, 1111, 2016, 3,
001, 2222, 2016, 15,
002, 2222, 2015, 6,
002, 2222, 2016, 10,
002, 1111, 2016, 12,
Here, the reservation is calculated based on the total product in table 2 and the number of product reserved in table 1. for exemple, on 2014, we have reservation 5 for ID_M = 001 in table 1, we search the ID_M = 001 in table 2, we reserve first for the product in priority 1, so it's ID_type 3333. so we get first line in the desired table: 001, 3333, 2014, 5.
on 2015, we have 10 reservations in table 1, so we will first use the product left from 2014 for ID_Type 3333, and then we use the product ID_Type 1111, the left product for ID_type 3333 is 3 (8-5), so the left reservation 7 (10-3) is for the ID_Type 1111. therefore we have got the 2nd and 3rd lines from the desired table 3:
001, 3333, 2015, 3, 001, 1111, 2015, 7,