根据日期的不同频率查找下一个发生日期

时间:2019-05-31 13:52:55

标签: postgresql

我目前正在尝试跟踪用户的支出金额以及他们的上次付款日期。

我最头疼的问题是如何根据不同的付款频率(每周,每月,每季度,每年)计算这些日期

示例:

用户说他们的付款于2019年1月20日开始 他们每月付款,所以最后一次付款应该是05/20/2019

我使用的是Postgres数据库,首先尝试在选择查询中放置一个case语句。

select 
    id,
    userid,
    companyid,
    value,
    case
        when frequency = 1 then 
            generate_series(startdate, created_at, '1 week')
        when frequency = 2 then 
            generate_series(startdate, created_at, '1 month')
                when frequency = 3 then 
            generate_series(startdate, created_at, '3 month')
                when frequency = 4 then 
            generate_series(startdate, created_at, '1 year')
        end
    from public.business_expenditures;

因此,如果此SQL错误未出现,它将不会返回预期的结果,因为它将创建所有已付款的列表:

错误:在CASE中不允许返回设置功能 提示:您也许可以将返回设置的函数移至LATERAL FROM项中。

然后我尝试了

select 
    be.id,
    be.userid,
    be.companyid,
    be.value,
    be.frequency,
    be.startdate,
    MAX(testing) as last_payment_date
from public.business_expenditures be left join lateral
    generate_series(be.startdate, be.created_at, '1 month') as testing
    on be.frequency = 2
    group by be.id;

这确实在last_payment_date列中返回了预期的结果,但它仅返回了具有每月频率的那些人的日期。这是预料之中的,我不知道该如何检查其他频率。我觉得解决方案是在生成一系列日期之前放置IF语句或大小写,但是在尝试此类操作时遇到语法错误

select 
    be.id,
    be.userid,
    be.companyid,
    be.value,
    be.frequency,
    be.startdate,
    MAX(testing) as last_payment_date
from public.business_expenditures be left join lateral
    if be.frequency = 3 then 
        generate_series(be.startdate, be.created_at, '1 month') as testing
        on be.frequency = 3
    elsif be.frequency = 4 then
        generate_series(be.startdate, be.created_at, '3 month') as testing
        on be.frequency = 4
    end if;
    group by be.id;

0 个答案:

没有答案