CREATE OR REPLACE VIEW V_CURRENT_PARTY_ADDRESSES AS
SELECT *
FROM (SELECT parties.id,
       addresses.code AS address_code,
       addresses.sub_building,
       addresses.building,
       addresses.street,
       addresses.city,
       addresses.postcode,
       party_addresses.start_date,
       party_addresses.end_date,
       party_addresses.comments,
       party_address_roles.rt_code,
       MAX(party_addresses.start_date) over(PARTITION BY parties.ID, rt_code) AS max_start_date
  FROM addresses,
       party_addresses,
       party_address_roles,
       parties
 WHERE addresses.code = party_addresses.addr_code
       AND party_addresses.start_date = party_address_roles.paddr_start_date
       AND party_addresses.addr_code = party_address_roles.paddr_addr_code
       AND party_addresses.prty_id = party_address_roles.paddr_prty_id
       AND parties.id = party_addresses.prty_id)
 WHERE start_date = max_start_date
 ORDER BY 1;
