<sub><em>Contributions originally left as comments</em></sub>

I typically aggregate dynamic columns into a single JSON value these days rather than creating dynamic columns for each attribute. That might be a challenge though as well, with your outdated (and unsupported) Postgres version - [a-horse-with-no-name][1]

The desired output can't be obtained directly in SQL. You need to write a query that generates the query that generates your desired output. Giving up on your desired output and producing JSON instead may also be considered, as it would be simpler. - [Daniel Vérité][2]

---

<!-- add your contribution here -->

  [1]: https://dba.stackexchange.com/users/1822/a-horse-with-no-name
  [2]: https://dba.stackexchange.com/users/7119/daniel-v%C3%A9rit%C3%A9