That SQL looks pretty complicated Where are the tests
My standard development technique with PostgreSQL is to hack away in Emacs, try things out on live data, and eventually build up working queries and functions. This "test as you go" approach works well for small projects, but for really hard problems the result is usually hundreds of lines of SQL that looks a lot like an object lesson in unmaintainable code.