如何调试这个交叉表() Postgres 函数



Current Table data

表名称:应用程序应用

id  | applied_class  |  applied_date
----+-------+-------------------------------
 27 | city1          | 2013-03-11 23:47:04.167624-04
 28 | city1          | 2013-03-11 23:58:28.90088-04
 29 | city2          | 2013-03-12 00:39:05.955988-04
 30 | city3          | 2013-03-12 01:07:28.30229-04
 31 | city2          | 2013-03-12 09:46:32.778106-04
 32 | city1          | 2013-03-12 23:06:52.262773-04
 33 | city2          | 2013-03-14 14:28:40.401831-04
 34 | city3          | 2013-03-15 19:33:59.346832-04
 35 | city2          | 2013-03-16 05:51:11.354835-04

所需的输出。

它是一段时间内记录的聚合计数,按日期(天)和城市分组。

date        |  city1   |  city2   |  city3 
------------+----------+----------+--------
2013-03-11  |   2      |   0      |    0        
2013-03-12  |   3      |   2      |    1
2013-03-13  |   3      |   2      |    1
2013-03-14  |   3      |   3      |    0    
2013-03-15  |   3      |   3      |    2
2013-03-16  |   3      |   3      |    0

当前(失败)查询

我正在尝试逐步完成查询,但遇到了障碍。 下面的查询返回以下错误(请注意,当我在交叉表之外自行运行这些查询时,这些查询都可以工作):

详细信息:SQL rowid 数据类型与返回的 rowid 数据类型不匹配。

select *
from crosstab(
    $$select temp_table.d,  
       applied_class,  
       sum(temp_table.ct) over (order by d) 
    from   
       (
        select count(id) ct, 
               applied_class, 
               date_trunc('day', applied_date) d from application_app 
        where applied_class like '%L13' 
        group by applied_class, d 
        order by d
        ) as temp_table
    order by 1, 2$$)  -- end crosstab
as ct ("day" date, "city1" text, "city2" text, "city3" text);

回答一篇旧帖子,因为我没有找到任何帮助我解决类似问题的具体内容。在我的查询中,行列是 2 个 varchar 的集合,交叉表的输出也是 varchar。这给出了 rowid 错误。在交叉表输出中将 varchar 更改为文本消除了该错误。

select * from crosstab(
    'select concat(.....) '
    ) as
ct(dname text,
ct1 float, ...;

首先,阅读文档

在我看来,您需要将日期字段重命名为"row_name",将"applied_class"重命名为"类别"。

您必须问的基本问题是"函数如何知道根据什么标准来透视我的数据? 一旦你有了它,它就更容易了。

编辑:你和我正在查看该函数的两个不同版本。 第一个,我上面描述的那个,是你实际使用的那个(只有一个参数,文本sql)。 在第二个版本中,您可以自己提供交叉表标准,在这方面,类别被指定为第二个参数。

您需要选择一种或另一种方式来做到这一点。

最新更新