.net 用于根据销售额将预算分解为一个月的剩余天数的SQL查询逻辑

slmsl1lt  于 2023-03-04  发布在  .NET
关注(0)|答案(1)|浏览(121)

我有一个销售和预算表,包含日期。我需要计算差额和New_Budget(取决于销售和差额)

CREATE TABLE MasterData (
Business_Date DATE,
Sales float,
Budget float,
Difference_Budget float,
New_Budget float
);

INSERT INTO MasterData VALUES
('2023-03-01', 100, 150, 0, 0),
('2023-03-02', 200, 190, 0, 0),
('2023-03-03', 0, 180, 0, 0);

表格数据:

我需要计算差异和新预算,如下所示:

差异预算=(预算-销售)
New_Budget = Budget + Difference_Budget(差异预算被分解为该月的剩余天数)
新预算示例:
对于日期1(始终为New_Budget =预算)
对于日期2(日期1的差额50除以该月的剩余天数。50/30 = 1.67)(因此,新预算=(190 + 1.67)= 191.67)
对于日期3(新预算=(180 + 1.67 + 0.34)= 182.01)。(计算方法为50/30 = 1.67(日期1)和10/29 = 0.34(日期2))。
差额预算需要拆分为当月的剩余天数。
我需要SQL选择查询的C#编码的目的。

exdqitrt

exdqitrt1#

下面是代码。你需要使用滞后和求和函数来实现结果:

drop table if exists #a 
drop table if exists #b

CREATE TABLE #a (
Business_Date DATE,
Sales float,
Budget float
);

INSERT INTO #a VALUES
('2023-03-01', 100, 150),
('2023-03-02', 200, 190),
('2023-03-03', 0, 180)

--- Find prevous value of Difference_Budget and prev value of day of Business_Date and subtract it from total days in month
select *,(case when day(Business_Date) = 1 then 0 else lag(Difference_Budget,1) over (order by Business_Date) end )  as New_Budget_previous_day,
isnull(day(dateadd(day,-1,dateadd(month,1,DATEFROMPARTS(year(Business_Date),month(Business_Date),1)))) - day(lag(Business_Date,1) over (order by Business_Date)),0) as total_No_Days
into #b
from
(
select * , 
       abs(case when sales = 0 then 0 else budget - sales end) as Difference_Budget
       
from #a
)as a

--Calculating Running_total_remaining_days by using sum function and then adding its value to budget
select *,sum(remaining_days) over (partition by year(Business_Date),month(Business_Date) 
                                   order by Business_Date 
                                   rows between unbounded preceding and current row
                                ) as Running_total_remaining_days,

        budget + sum(remaining_days) over (partition by year(Business_Date),month(Business_Date) 
                                   order by Business_Date 
                                   rows between unbounded preceding and current row
                                ) as New_budget
from
(
select * , cast(case when total_No_Days = 0 then 0 else New_Budget_previous_day/total_No_Days end as decimal(3,2)) as remaining_days
from #b
) as a

相关问题