简体   繁体   English

Postgres pivot 没有交叉表

[英]Postgres pivot without crosstab

I am using a Postgres instance with relatively limited functionality - for example, the crosstab() function is not available.我正在使用功能相对有限的 Postgres 实例 - 例如, crosstab() function 不可用。 My objective is to pivot a table so that dates in ym are arranged as columns in ascending order by date, for example:我的目标是 pivot 一个表,以便ym中的日期按日期升序排列为列,例如:

input:输入:

group_code  ym  total
foo 2020-11-01  17
foo 2020-12-01  19
bar 2020-09-01  21
baz 2020-10-01  23

output: output:

group_code 2020-09-01 2020-10-01 2020-11-01 2020-12-01
foo        NULL       NULL       17         19
bar        21         NULL       NULL       NULL
baz        NULL       23         NULL       NULL

The key here, however, is that the number of unique dates is not known in advance, and that group codes without values for a specific date should be NULL in the resulting table.然而,这里的关键是唯一日期的数量是事先不知道的,并且没有特定日期值的组代码在结果表中应该是 NULL。 Is there an elegant workaround in postgres to create such an output table without hardcoding all of the dates in advance with CASE WHEN statements and FULL OUTER JOIN s - in other words - dynamically?在 postgres 中是否有一种优雅的解决方法来创建这样的 output 表,而无需使用CASE WHEN语句和FULL OUTER JOIN预先对所有日期进行硬编码 - 换句话说 - 动态? Any suggestions would be appreciated任何建议,将不胜感激

You can use filtered aggregation:您可以使用过滤聚合:

select group_code, 
       max(total) filter (where ym = date '2020-09-01') as "2020-09-01",
       max(total) filter (where ym = date '2020-10-01') as "2020-10-01",
       max(total) filter (where ym = date '2020-11-01') as "2020-11-01",
       max(total) filter (where ym = date '2020-12-01') as "2020-11-02"
from the_table
group by group_code;

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

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