下面是我的桌子结构。我需要计算每项物业的租期租金:
让我们看看PropertyID = 12077:
由于这份物业租约是在2023年至2028年之间开始和结束的,我想知道(每年分别收取)租金的数额。这将考虑到每12个月增加一个百分点(复合租金增加)。
示例:
21.53 * 1280将提供头12个月的租金。然而,租赁于2月份开始,因此2023年的租金总额为=(21.23*1280/12)* 11。
2024年的第一个月租金为(21.23 * 1280)/12,因为租金每12个月只增加一次。2024年的未来11个月,租金为(12.23* 1.04 * 1280)/12)* 11。
2025年,第一个月的租金为(12.23 * 1.04 *1280)/12)。然而,2025年的未来11个月将是((12.72 * 1.04 *1280)/12)*11.12.72来自复合增长。
我要怎么做才能做到这一点呢?最让我困惑的是,我不知道如何适应租赁开始日期,当它不是从1月开始。
declare @table table
(
PropertyID int,
area int,
StartDate date,
EndDate date,
BaseRent decimal(12,2),
RentIncreaseBasis varchar(30),
RentIncreasePercent decimal(5,2),
IncreaseRepeatMonths int
)
insert @table values (12076, 5627, '2024-01-01', '2028-12-31', '16.52', '% Increase', 0.03, 12)
insert @table values (12077, 1280, '2023-02-01', '2027-10-31', '21.53', '% Increase', 0.04, 12)
insert @table values (12078, 1000, '2017-03-01', '2025-11-30', '23.52', '% Increase', 0.01, 12)
insert @table values (12079, 2000, '2020-02-01', '2024-09-30', '15.57', '% Increase', 0.05, 12)
insert @table values (12080, 3000, '2018-05-01', '2020-08-31', '18.58', '% Increase', 0.04, 12)
insert @table values (12081, 4000, '2019-08-01', '2020-12-31', '22.56', '% Increase', 0.03, 12)
insert @table values (12082, 5000, '2017-02-01', '2028-03-31', '19.53', '% Increase', 0.02, 12)
select * from @table
发布于 2017-11-15 06:35:50
我建议使用包含表中所有月份的日历表。我希望我的例子能在SQL 2008中奏效。
-- here is your code
-- the calendar table
DECLARE @MonthCalendar table(
[Month] date PRIMARY KEY
)
DECLARE @MinDate date,@MaxDate date
-- get min and max date
SELECT
@MinDate=MIN(StartDate),
@MaxDate=MAX(EndDate)
FROM @table
-- fill the calendar table
;WITH monthCTE AS(
SELECT CAST(@MinDate AS date) [Month]
UNION ALL
SELECT DATEADD(MONTH,1,[Month])
FROM monthCTE
WHERE [Month]<@MaxDate
)
INSERT @MonthCalendar([Month])
SELECT [Month]
FROM monthCTE
OPTION(MAXRECURSION 0);
-- final query
SELECT
*,
(BaseRent*Area*(1+RentIncreasePercent*IncreaseCount))/12 MonthRentAmount,
(1+RentIncreasePercent*IncreaseCount) TotalPercent
FROM
(
SELECT *,(ROW_NUMBER()OVER(PARTITION BY t.PropertyID ORDER BY m.[Month])-1)/12 IncreaseCount
FROM @table t
JOIN @MonthCalendar m ON m.[Month] BETWEEN t.StartDate AND t.EndDate
--WHERE t.PropertyID=12077
) q
-- query for total amounts by PropertyIDs and Years
SELECT
PropertyID,
YEAR(StartDate) [Year],
SUM((BaseRent*Area*(1+RentIncreasePercent*IncreaseCount))/12) YearRentAmount
FROM
(
SELECT *,(ROW_NUMBER()OVER(PARTITION BY t.PropertyID ORDER BY m.[Month])-1)/12 IncreaseCount
FROM @table t
JOIN @MonthCalendar m ON m.[Month] BETWEEN t.StartDate AND t.EndDate
--WHERE t.PropertyID=12077
) q
GROUP BY PropertyID,YEAR(StartDate)
ORDER BY PropertyID,[Year]
https://stackoverflow.com/questions/47294748
复制相似问题