交叉连接生成系列日期

时间:2018-03-19 18:53:06

标签: sql postgresql cross-join generate-series

我试图根据“dtleasefrom”(租约开始日期)计算一个月内续租的租户数量。但是,我想将每次续订归结为最后一次租约结束的月份,并将其与生成的一系列日期联系起来,这些日期可用于转动。但是,我似乎无法弄清楚为什么unit_month_date不等于dtleaseto日期。请参阅下面的图片和代码。

enter image description here

Select
ten.scode as leasename
,th.sevent as event_type
,th.dtoccurred as date_occurred
,unit.scode as unit
,p.scode as property
,th.dtapply as apply_date
,th.dtapprove as approve_date
,th.dtsigndate as sign_date
,th.dtmovein as move_in_date
,th.dtmoveout as move_out_date
,th.dtleasefrom as lease_from
,th.dtleaseto as lease_to
,th.dtnotice as notice_date
,th.crent as rent
,att.subgroup2 as zone
,(ten.sfirstname || ' ' ||  ten.slastname) as tenant_name
,pm.property_manager as property_manager
,(case when date_trunc('month',th2.b) = dd.month::date and th2.row_numba = 1 and th.sevent = 'Lease Signed' then 1 else 0 end) as Leases_Ending
,dd.month::date as unit_month
,(case when date_trunc('month',th2.b) = dd.month::date and EXTRACT(day from age(th.dtleasefrom,th2.b)) <= 60  and EXTRACT(day from age(th.dtleasefrom,th2.b))  >= 0 and th2.row_numba = 1 and th.sevent = 'Lease Renewal' then 1 else 0 end) as Renewals
,(case when date_trunc('month',th2.b) = dd.month::date and EXTRACT(day from age(th.dtleasefrom,th2.b)) <= 60  and th2.row_numba = 1 and  th.sevent = 'Lease Renewal' then 1 else 0 end) as Renewals_All_In
,(case when th.istatus not in (1,2) and date_trunc('month',th2.b) < dd.month::date and th.sevent = 'Lease Signed'  then 1 else 0 end) as MTM_tenant
,th2.row_numba
,th.hmy
FROM
yardi.tenant ten
JOIN yardi.Tenant_History th  on ten.hmyperson = th.htent
CROSS JOIN (SELECT generate_series('05-01-2017'::date,'01-01-2020','1 month') as month) dd
JOIN (SELECT th.htent as a , date_trunc('month',th.dtleaseto) as b, Row_Number() over(partition by th.htent order by th.hmy) as Row_Numba FROM yardi.tenant_history th group by th.htent,th.dtleaseto,th.hmy ) th2 on th2.b = dd.month and th.htent = th2.a
JOIN yardi.unit on unit.hmy = th.hunit
JOIN yardi.property p on p.hmy = unit.hproperty
JOIN yardi.attributes att on att.hprop = p.hmy
JOIN yardi.propbut_property_management pm on pm.hcode = p.hmy

WHERE ten.istatus < 6 and th2.row_numba = 1

0 个答案:

没有答案
相关问题