CRudiger February 2016

rank over partition

I have a total of 3 tables. One table is called CONTACTINFO with CNTCT_ID as a primary index.

Second table is CONTACTMAP which links a customer(CUSTNUM) to all the contactinfo (details suchs as name, position, phone number etc).

Final table is a complete customer list, with one column that has a revolving list of all our customers.

My code below pulls back the most recent entry for custnum 84574. But I need it pull back results for all custnum in the complete customer list custlist.

select 
     A. CUST_TYPE
    ,A.CINSERT_DT
    ,A.CNTCT_ID

from CONTACTINFO a

JOIN  CONTACTMAP B
ON A.CNTCT_ID = B.CNTCT_ID

where       b. CUSTNUM in (‘84574’)
and         A. CUST_TYPE in (‘PAYER’)

qualify rank() over (partition by a. CUST_TYPE order by A. CINSERT_DT desc) = 1

Here are my tables CONTACTINFO TABLE

CNTCT_ID    CUST_TYPE
1           PAYER
2           OWNER
3           BUYER

CONTACTMAP Table

 CNTCT_ID       CUSTNUM
1           84574
2           99457   
3           54187   

TABLE3

 CUSTNUM
84574
99457   
54187   

Answers


dnoeth February 2016

Simply join table #3 on CUSTNUM and change the PARTITION BY to CUSTNUM instead of CUST_TYPE:

select 
     A. CUST_TYPE
    ,A.CINSERT_DT
    ,A.CNTCT_ID

from CONTACTINFO a

JOIN  CONTACTMAP B
ON A.CNTCT_ID = B.CNTCT_ID
JOIN custlist as c
ON b.CUSTNUM = c. CUSTNUM

--maybe remove the condition and add CUST_TYPE to PARTITION BY if you want one row per type
where A.CUST_TYPE in (‘PAYER’)

qualify
  rank()
  over (partition by c.CUSTNUM 
        order by CINSERT_DT desc) = 1

Post Status

Asked in February 2016
Viewed 3,647 times
Voted 4
Answered 1 times

Search




Leave an answer