here is my sql query and sample data to test (you can modify as you like): https://dbfiddle.uk/?rdbms=postgres_13&fiddle=5c816a5d3c878846e9c5f0d133b431df
I have a