-- schema version 35 to 36

CREATE VIEW v_member AS
SELECT m.mgnr, m.name,
       (COALESCE(m.prefix || ' ', '') || m.given_name || COALESCE(' ' || m.middle_names, '') || COALESCE(' ' || m.suffix, '')) AS other_names,
       m.address, p.plz, o.name AS locality,
       a.name AS billing_name, a.address AS billing_address, p2.plz AS billing_plz, o2.name AS billing_locality,
       k.name AS default_kg,
       GROUP_CONCAT(e.address, ', ') AS email_addresses
FROM member m
    LEFT JOIN AT_plz_dest p ON p.id = m.postal_dest
    LEFT JOIN AT_ort o ON o.okz = p.okz
    LEFT JOIN member_billing_address a ON a.mgnr = m.mgnr
    LEFT JOIN AT_plz_dest p2 ON p2.id = a.postal_dest
    LEFT JOIN AT_ort o2 ON o2.okz = p2.okz
    LEFT JOIN AT_kg k ON k.kgnr = m.default_kgnr
    LEFT JOIN member_email_address e ON e.mgnr = m.mgnr
GROUP BY m.mgnr
ORDER BY m.mgnr;
