Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 无交叉表的Postgres轴_Sql_Postgresql_Pivot - Fatal编程技术网

Sql 无交叉表的Postgres轴

Sql 无交叉表的Postgres轴,sql,postgresql,pivot,Sql,Postgresql,Pivot,我使用的是一个功能相对有限的Postgres实例,例如,crosstab()函数不可用。我的目标是透视表,以便ym中的日期按日期升序排列为列,例如: 输入: group_code ym total foo 2020-11-01 17 foo 2020-12-01 19 bar 2020-09-01 21 baz 2020-10-01 23 输出: group_code 2020-09-01 2020-10-01 2020-11-01 2020-12-01 foo NU

我使用的是一个功能相对有限的Postgres实例,例如,
crosstab()
函数不可用。我的目标是透视表,以便
ym
中的日期按日期升序排列为列,例如:

输入:

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

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

然而,这里的关键是,唯一日期的数量事先不知道,并且没有特定日期值的组码在结果表中应该为空。在postgres中是否有一个优雅的解决方法来创建这样一个输出表,而不必使用
CASE WHEN
语句和
完全外部连接时的所有日期进行硬编码,换句话说,是动态的?如有任何建议,将不胜感激。

您可以使用过滤聚合:

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;

如果您想要动态列,那么您需要动态SQL—这比纯SQL更复杂。这是否回答了您的问题?