简体   繁体   中英

Postgres pivot table with crosstab

I have a table like the next one:

+------------+---------+---------+---------+
|    date    | value 1 | value 2 | value 3 |
+------------+---------+---------+---------+
| 01/01/2017 |     263 |       7 |     222 |
| 02/01/2017 |     275 |      -9 |     209 |
| 03/01/2017 |     331 |      -9 |     243 |
| .          |       . |       . |       . |
| .          |       . |       . |       . |
| .          |       . |       . |       . |
+------------+---------+---------+---------+

I want to create this other one in postgres:

+---------+---------------+------------+------------+
|         |    01/01/2017 | 02/01/2017 | 03/01/2017 |
+---------+---------------+------------+------------+
| value 1 |           263 |        275 |        331 |
| value 2 |             7 |         -9 |         -9 |
| value 3 |           222 |        209 |        243 |
+---------+---------------+------------+------------+

But my problem is that I dont know how many dates I will have, so I have to use something like this:

SELECT * FROM crosstab(
  $$ SELECT value1, date  FROM myTable ORDER BY 1 $$,
  $$ SELECT m FROM generate_series((select min(date) from myTable) ,(select max(date) from myTable), '1 month'::interval) m $$
) AS (
  ".." date, ".." date, ".." date, ".." date
);

Does someone can help me? Thanks.

Your basic issue is that PostgreSQL needs to know what the columns look like in order to plan the query. Consequently you need to return some sort of fixed-column structure. There are a number of ways you can do this:

  1. Query dates first or allow them to be input, and then generate your query in the db client.
  2. Wrap this in a stored procedure which returns a refcursor
  3. Wrap in a stored procedure which returns a list of JSON representations of rows.

But either way you cannot do it in a query without dynamically generating the query somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM