PostgreSQL 交叉表:月行和日列;错误 rowid 数据类型与返回 rowid 数据类型不匹配

Dys*_*i_A 5 postgresql crosstab

我正在尝试创建一个交叉表,其中行=月,列=天(即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 |      |     |     |     |     |     |     |     |     |      |
Run Code Online (Sandbox Code Playgroud)

我的查询如下:

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
)
Run Code Online (Sandbox Code Playgroud)

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

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

我感觉这是一个简单的修复,希望得到任何帮助。谢谢!

kli*_*lin 7

有两个问题。中的行声明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"
)
Run Code Online (Sandbox Code Playgroud)

rextester 中的工作示例。