雪花中的Rownum()

时间:2018-10-30 15:54:29

标签: sql window-functions ansi-sql snowflake

select distinct e.acct_id as ACCOUNT_IDENTIFIER, a.form_id,a.agt_ent_user_id,substr(form_sbmt_ts,1,10) as form_dt,e.ACCT_SFX_NUM,
            b.form_nm,c.src_load_publn_ts,d.CSTM_DATA_42,e.CR_RVKD_STAT_CD,e.CLSD_REAS_CD,e.SVC_OWNR_CD,
            e.CHRGOF_REAS_CD,e.SCURT_FRD_STAT_CD,
            c.current_cnt_plcy_id,f.current_brv_plcy_id,row_number() over (partition by e.acct_id order by substr(form_sbmt_ts,1,10) desc)as rn
            from DB.pcdw.ir_afe a
            join DB.pcdw.ir_form b on a.form_id=b.form_id
            left join (select X.acct_id,X.plcy_id,x.plcy_type_cd,x.src_load_publn_ts, case when X.plcy_type_cd = 'CNT' THEN X.plcy_id  end as current_cnt_plcy_id ,
                       row_number() over (partition by x.acct_id order by x.src_load_publn_ts)=1
                       from DB.pcdw.pc_acct_plcy X   
                    where x.plcy_type_cd in ('CNT')  ) c on a.acct_id=c.acct_id
            left join (select X.acct_id,X.plcy_id,x.plcy_type_cd,x.src_load_publn_ts, case when X.plcy_type_cd = 'BRV' THEN X.plcy_id  end as current_brv_plcy_id,
                       row_number() over (partition by x.acct_id order by x.src_load_publn_ts)=1
                       from DB.pcdw.pc_acct_plcy X  
                    where x.plcy_type_cd in ('BRV')) f on a.acct_id=f.acct_id
            left join DB.pcdw.t2_acct_snap_bc d on a.acct_id=d.acct_id
            left join DB.PCDW.T2_ACCT_STAT_HIST_BC e on a.acct_id=e.ACCT_ID
            where substr(cast(form_sbmt_ts as varchar(40)),1,10)>= DATEADD(Day,-8,current_date)
            and a.acct_id is not null and b.form_nm in ('GM Extended Family Upgrade','GM BuyPower Upgrade')
            and c.plcy_type_cd in ('BRV','CNT') 
            and e.SVC_OWNR_CD in('000099','000100')
            and e.ACCT_SFX_NUM = 0
            and rn=1
            order by form_dt

当我在where条件中使用rn = 1时,它会引发错误,并且当我在select子句中使用row_number()进行划分(按e.acct_id顺序按substr(form_sbmt_ts,1,10)= 1划分)不删除重复项

1 个答案:

答案 0 :(得分:0)

我无法测试此代码,但是每当我在子查询中使用RowNumber时,就好像是此示例...

left join (
select X.acct_id,X.plcy_id,x.plcy_type_cd,x.src_load_publn_ts, case when X.plcy_type_cd = 'CNT' THEN X.plcy_id  end as current_cnt_plcy_id ,
row_number() over (partition by x.acct_id order by x.src_load_publn_ts)=RN
from DB.pcdw.pc_acct_plcy X   
where x.plcy_type_cd in ('CNT')  
) c on a.acct_id=c.acct_id and c.rn=1