【问题标题】:How do i calculate a projection sum using sql?如何使用 sql 计算投影总和?
【发布时间】:2016-08-23 15:45:55
【问题描述】:

我有以下租约表

Lease_id Apt_id Resident_id Start_Date End_Date   Upfront_Amt Monthly_Fee
101      110    1001        02/01/2015 07/31/2015 250          500
102      111    1002        03/01/2015 02/29/2016 1000         2000
103      112    1003        04/01/2015 03/31/2016 750          1500

我想计算的是月费收入的预测。 例如:

01/2015 0 (No lease active)
02/2015 500 (From Lease 101)
03/2015 500 + 2000 (From Lease 101 and 102)
04/2015 500 + 2000 + 1500 (From Lease 101, 102 and 103)
:
:
08/2015 2000 + 1500 (From lease 102 and 103)
etc..

有没有办法通过单个查询有效地做到这一点?

【问题讨论】:

    标签: sql database sum projection


    【解决方案1】:
    select
        format(m.Lease_Month, 'MMM yyyy') as Lease_Month,
        sum(sum(Monthly_Fee)) over (partition by m.Lease_Month) as Projection
    from
        <list of months> m left outer join
        Lease l
            on m.Lease_Month between l.Start_Date and l.End_Date
    group by
        m.Lease_Month
    order by
        m.Lease_Month;
    

    有很多方法可以生成月份列表。这是一个:

    declare @num_Months int = 16;
    declare @start_Date date = '20150101';
    
    with months as (
        select @start_Date as Lease_Month, 1 as Month_Num
        union all
        select dateadd(month, Month_Num, @start_Date), Month_Num + 1
        from months
        where Month_Num < @num_Months
    ) ...
    

    把它们放在一起,看看它在这里运行:http://rextester.com/YUAF69376

    【讨论】:

    • 谢谢你,它工作得很好,我可以使用数据库中的一个日历表,它快速高效。再次感谢。关于我可以在哪里学习这样的高级 sql(对我来说是高级的)有什么建议吗?
    • @MadhuraKshirsagar 我希望我能给您指出一个教程/参考资料,但我只是不知道有什么好推荐的。你了解多少?
    【解决方案2】:

    这样的事情可能会奏效:

    SELECT l1.[Start_Date], SUM(l2.SumFee)
    FROM Lease as l1, (SELECT [Start_Date],SUM(Monthly_Fee) As SumFee
    FROM Lease
    GROUP BY [Start_Date]) as l2
    WHERE l1.[Start_date]>=l2.[Start_Date]
    GROUP BY l1.[Start_Date]
    

    另一种方法是:

    SELETC l1.Start_Date, l1.Monthly_Fee, SUM(l2.Fee) as CumulativeSum
    FROM Lease as l1
    INNER JOIN Lease as l2 ON l1.Start_Date >= l2.Start_Date
    GROUP BY l1.Start_Date, l1.Monthly_Fee
    ORDER BY l1.Start_Date
    

    【讨论】:

    • 干得好,但值得指出的是,方括号仅适用于 MSSQL。如果 Madhura 正在使用其他任何东西,他们将需要删除它们。
    • 不幸的是,您的结果是累积的。巧合的是,前三个月/租约“有效”,但这并不是问题所在:(基本上它只关注租约的第一个月。
    猜你喜欢
    • 2015-05-03
    • 2019-05-25
    • 2021-06-08
    • 2019-05-05
    • 1970-01-01
    • 2021-04-09
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多