Unexpected duplicates in result of crosstab function

Solution 1:

The input needs to be sorted. Append ORDER BY 1 to the first argument of your first query.

Also, it makes no sense to query all release_year dynamically for the second argument while the column definition list is static anyway.

See:

  • PostgreSQL Crosstab Query

To replace resulting NULL values, use COALESCE in the outer SELECT. Example:

  • Use row values as columns in PostgreSQL