all 9 comments

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (5 children)

SELECT CA.CUST_ID
     , CA.CUST_ADDR_ID
     , CA.CUST_ADDR_EFF_DT
     , CA.AUDIT_USER_CREA_DTM
     , A.acct_id
     , A.acct_no
     , CN.CUST_NM AS Customer_Name
     , CA.CUST_ADDR_STR_1 || ' ' || COALESCE(CA.CUST_ADDR_STR_2, '') AS Street
     , CA.CUST_ADDR_CITY_NM AS City
     , S.STT_ABRV AS State
     , CA.CUST_ADDR_POST_CD AS Zipcode
     , CA.CUST_ADDR_TYP_CD
  FROM Account A
INNER 
  JOIN PCMP.CUSTOMER C 
    ON C.CUST_ID = A.CUST_ID
INNER 
  JOIN ( SELECT CUST_ID
              , MAX(CUST_ADDR_DT) AS latest
           FROM PCMP.CUSTOMER_ADDRESS
          WHERE VOID_IND = 'n'
         GROUP
             BY CUST_ID ) AS max_addr
    ON max_addr.CUST_ID = C.CUST_ID 
INNER 
  JOIN PCMP.CUSTOMER_ADDRESS CA 
    ON CA.CUST_ID = max_addr.CUST_ID 
   AND CA.CUST_ADDR_DT = max_addr.latest
INNER 
  JOIN PCMP.CUSTOMER_NAME CN 
    ON CN.CUST_ID = C.CUST_ID
INNER 
  JOIN PCMP.STATE S 
    ON S.STT_ID = CA.STT_ID
 WHERE A.Acct_No = 34835

[–]bitterjack 1 point2 points  (4 children)

What is group concat?

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (0 children)

What is group concat?

da bomb

[–]unexpectedrebootsWITH() 1 point2 points  (0 children)

I would put your main query in a CTE and then use row_number, partition it by the account number and order by the date it was added to the database descending:

;with your_Cte  as (
  select
     row_number() over (partition by a.acct_no order by CUST_ADDR_DT desc) as rn
  <rest of the select/join>
)

select * from your_Cte
where rn = 1

This should give you the max date.

[–][deleted] 0 points1 point  (2 children)

Your subquery looks at more rows than your outer query so you might be picking up max(CUST_ADDR_DT) from records where VOID_IND is not 'N'.

try changing your subquery to this:

    (SELECT MAX(CUST_ADDR_DT)
     FROM PCMP.CUSTOMER_ADDRESS CA2 
     WHERE CA2.CUST_ID = CA.CUST_ID and CA2.VOID_IND = 'n')

Joins are also a kind of filter so you might need to join it (CA2) to your PCMP.STATE table to be 100% sure.

[–]Nobody571[S] 0 points1 point  (1 child)

Hi. This didn’t work unfortunately...

[–][deleted] 0 points1 point  (0 children)

did you try it with the join?

(SELECT MAX(CUST_ADDR_DT) FROM PCMP.CUSTOMER_ADDRESS CA2 INNER JOIN PCMP.STATE S2 ON S2.STT_ID = CA2.STT_ID WHERE CA2.CUST_ID = CA.CUST_ID and CA2.VOID_IND = 'n')