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

时间:2018-09-24 20:23:18

标签: 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 |      |     |     |     |     |     |     |     |     |      |

我的查询如下:

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数据类型不匹配

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

我觉得这是一个简单的解决方法,希望能对您有所帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

有两个问题。 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.