Hi Andreas and Mario,
Many thanks for your suggestion to use PostgreSQL's window function,exactly what I needed.
kind regards,Jan