Hi All,
I have the tables below and like to join them based on PropCode, Month and Year so that the RentLoss is calculated based on the Market Rent in the particular month.
@MR - stored the Market Rent values
@void - stores details when a property got empty and filled
Query: join @MR and @void such that the Market Rent amount from @MR is selected based on the VoidStartDate in @void
Declare @MR Table ( PropCode VARCHAR(10) ,MRFromDate date ,MR_Start_Month VARCHAR(10) ,MR_Start_Year INT ,MREndDate date ,MR_End_Month VARCHAR(10) ,MR_End_Year INT ,MARKET_RENT Money ) INSERT INTO @MR (PropCode, MRFromDate, MR_Start_Month,MR_Start_Year,MREndDate,MR_End_Month,MR_End_Year,MARKET_RENT) VALUES (3304,'2014/06/15','June',2014,'2014/11/30','November',2014,280) ,(3304,'2014/12/01','December',2014,'2015/04/19','April',2015,290) ,(3304,'2015/04/20','April',2015,'2050/01/01','January',2050,310) ,(3782,'2014/05/17','May',2014,'2014/07/21','July',2014,250) ,(3782,'2014/07/22','July',2014,'2014/11/14','November',2014,275) ,(3782,'2014/12/15','November',2014,'2050/01/01','January',2050,290) SELECT * from @MR
Declare @void Table ( PropCode VARCHAR(10) ,VoidStartDate date ,VoidMonth VARCHAR(10) ,VoidYear VARCHAR(10) ,LetDate date ,LetMonth VARCHAR(10) ,LetYear VARCHAR(10) ) INSERT INTO @void (PropCode,VoidStartDate,VoidMonth,VoidYear,LetDate,LetMonth,LetYear) VALUES (3304,'2014/07/15','July',2014,'2014/08/01','August',2014) ,(3782,'2014/05/17','May',2014,'2014/06/12','June',2014) ,(3782,'2014/11/28','November',2014,'2014/12/16','December',2014) select *, Datediff(Day, VoidStartDate,LetDate) as VoidDays from @void
Result:
PropCode VoidStartDate VoidMonth VoidYear LetDate LetMonth LetYear
VoidDays Market_Rent Loss
3304 2014-07-15 July 2014 2014-08-01
August 2014 17 280
4930
3782 2014-05-17 May 2014 2014-06-12
June 2014 26 250 6500
3782 2014-11-28 November 2014 2014-12-16 December
2014 18 290 5220
- Edited by jaggy99 1 hour 49 minutes ago