简体   繁体   English

带有交叉表的 Postgres 数据透视表

[英]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:我想在 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.您的基本问题是 PostgreSQL 需要知道列是什么样子才能计划查询。 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.首先查询日期或允许输入日期,然后在 db 客户端中生成您的查询。
  2. Wrap this in a stored procedure which returns a refcursor将其包装在一个存储过程中,该过程返回一个 refcursor
  3. Wrap in a stored procedure which returns a list of JSON representations of rows.包装在一个存储过程中,该过程返回行的 JSON 表示列表。

But either way you cannot do it in a query without dynamically generating the query somewhere.但是无论哪种方式,如果不在某处动态生成查询,就无法在查询中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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