I have seen that there are quit a few similar questions like this one, but I havent understood how to code it myself. Please have in mind that I am just a beginner in this f
The basic crosstab query for your example is simple:
SELECT * FROM crosstab(
'SELECT zoom, day, point
FROM province
ORDER BY 1, 2'
, $$VALUES ('2015-10-01'::date), ('2015-10-02')$$)
AS ct (zoom text, day1 int, day2 int);
But not with dynamic column names or a dynamic number of columns. As a compromise, you can have a fixed number of columns and only fill the leading ones. Basics:
crosstab_hash
is not going to help you with dynamic column names. It's for repeated use without typing a column definition list, but not for dynamic column names. Examples:
For truly dynamic column names, you need two round trips to the server. Whether you retrieve the column names with a first query to build a second query, or you create a cursor or a temporary table or a prepared statement. Whatever you try, you need two round trips. SQL wants to know the return type at call time.
The closest I could get to a "dynamic" call is with my custom crosstab_n()
function defined in this related answer:
Or you give up the idea of a completely dynamic crosstab query (because, you know, it's impossible) and use a two-step workflow, like mentioned above.
Let a function generate the crosstab query text. You can use the function provided here (and adapt it to your needs!):
In particular, remove GROUP BY 1, 2
, since you do not aggregate rows before the cross tabulation.
Execute the generated function.
For completeness, there is also the new \crosstabview metacommand in psql in Postgres 9.6 (just released) - with similar functionality, and it can display dynamic column names (attaching dynamic names happens in the psql client, not in the Postgres server).