sql - 我如何调试这个 crosstab() Postgres 函数?

标签 sql postgresql crosstab

当前表数据

表名:应用App

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

当前(失败)查询

我试图逐步完成查询,但遇到了瓶颈。下面的查询返回以下错误(请注意,当我在交叉表之外自行运行这些查询时,这些查询都有效):

DETAIL: SQL rowid datatype does not match return rowid datatype.

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, ...;

关于sql - 我如何调试这个 crosstab() Postgres 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19186563/

相关文章:

php - 在事务启动之前使用值的多个更新语句 MySQL

sql - 在 PostgreSQL 查询中从时间戳中省略 00 分钟

php - 通过 HTTP 将请求发送到 127.0.0.1,然后通过 HTTPS 转发

postgresql - 函数交叉表(未知,未知)不存在但确实存在

postgresql - 为什么这个 crosstab() 查询返回重复键?

java - 是否可以创建一个准备好的语句并稍后在 postgres 下使用 Java 重用它?

sql - "$$ 处或附近未终止的美元引号字符串

sql - PostgreSQL - 组合函数的 SELECT 和 RETURN VALUE

jasper-reports - 递增交叉表数据集时出错

带有变量的 SQLITE Case 表达式,以避免对表达式进行双重评估