【问题标题】:PostgreSQL Crosstab: Month rows and Day columns; Error rowid datatype does not match return rowid datatypePostgreSQL 交叉表:月行和日列;错误 rowid 数据类型不匹配 返回 rowid 数据类型
【发布时间】:2018-09-25 05:15:41
【问题描述】:

我正在尝试创建一个交叉表,其中行 = 月,列 = 天(即 1、2、3、4...31)。

    Month |   1  |   2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  10  | 11  |  12 ...
    ------+------+------+-----+-----+-----+-----+-----+-----+-----+-----+------+------
     9    | 1000 | 1500 |     |     |     |     | 500 |     |     |     | 1500 | 2000
     8    | 1000 |      |     |     |     |     |     |     |     |     |      |

我的查询如下:

SELECT * FROM crosstab(
    $$
    SELECT
      extract(month from created_at) AS themonth,
      extract(day from created_at) AS theday,
      COUNT(*)
    FROM public.users
    WHERE created_at >= Now() - Interval '90 Days' AND created_at < Now() - Interval '1 days'
    GROUP BY created_at
    ORDER BY 1,2
  $$
) AS final_result (
  themonth int,
    theday int
)

以下收到错误: rowid 数据类型不匹配返回 rowid 数据类型

这是我第一次使用交叉表。

我觉得这是一个简单的解决方法,希望能提供任何帮助。谢谢!

【问题讨论】:

  • 您选择了 3 列,而 final_result 只有两列?当然,只是注意到你的别名。

标签: postgresql crosstab


【解决方案1】:

有两个问题。 final_result 中的行声明必须与函数返回的元组完全匹配。此外,您应该使用带有两个参数crosstab(text source_sql, text category_sql) 的函数变体。

以 5 天为例:

SELECT * FROM crosstab(
    $$
    SELECT
      extract(month from created_at) AS themonth,
      extract(day from created_at) AS theday,
      COUNT(*)
    FROM public.users
    WHERE created_at >= Now() - Interval '90 Days' AND created_at < Now() - Interval '1 days' AND alternate_email not like '%@flyhomes.com%'
    GROUP BY created_at
    ORDER BY 1,2
    $$,
    $$
        SELECT generate_series(1, 5) -- should be (1, 31)
    $$
) AS final_result (
  themonth float, "1" bigint, "2" bigint, "3" bigint, "4" bigint, "5" bigint -- should be up to "31"
)

Working example in rextester.

【讨论】:

  • 谢谢,这完美解决了。我想可悲的是,我之前尝试过这个并且在某处有一个无关的“,”。感谢您帮助我停止用头撞墙。
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
相关资源
最近更新 更多