考虑下面的查询:

INSERT INTO     statement_line_items
SELECT      count(*)::integer as clicks, sum(amount_cents)::integer as amount_cents, imps.user_id, imps.created_at::date as statement_date
FROM        impression_events imps
INNER JOIN  transactions t ON t.event_id = imps.id
  AND       t.event_type = 'ImpressionEvent'
  AND       amount_cents >= 0
WHERE       imps.created_at >= (now() - interval '8 days')::date
  AND       imps.created_at < (now() - interval '7 day')::date
  AND       imps.clicked = true
GROUP BY    imps.user_id, imps.created_at::date;

这是回归:

ERROR:  column "statement_date" is of type date but expression is of type integer
LINE 2: ...icks, sum(amount_cents)::integer as amount_cents, imps.user_...
                                                             ^
HINT:  You will need to rewrite or cast the expression.

********** Error **********

ERROR: column "statement_date" is of type date but expression is of type integer
SQL state: 42804
Hint: You will need to rewrite or cast the expression.
Character: 117

我的语句行项目表 struct 如下:

"id";              "integer"
"user_id";         "integer"
"statement_date";  "date"
"description";     "character varying(255)"
"clicks";          "integer"
"amount_cents";    "integer"
"created_at";      "timestamp without time zone"
"updated_at";      "timestamp without time zone"

推荐答案

你把imps.userid分放在你的statement_date栏里.这必须失败.

count(*)::integer as clicks                   goes into id
sum(amount_cents)::integer as amount_cents    goes into userid
imps.user_id                                  goes into statement_date

要指定插入的顺序,可以执行以下操作:

INSERT INTO statement_line_items (col1, col2, ...)
values (select data_for_col1, data_for_col2, ...)

Postgresql相关问答推荐

通过窗口函数收集反连接结果?

列索引8上的扫描错误,名称已复制:不支持扫描,正在存储驱动程序.值类型[]uint8到类型*[]*bool

select语句的Jooq代码生成

Rust中使用sqlx的多线程postgres操作的惯用方法是什么?

PL/pgSQL中的IP递增函数

Gorm 创建表单数据文件上传错误

联合所有 postgresql Select 子句保留顺序

PG::UndefinedTable:错误:relation "active_storage_blobs" does not exist

如何在 PSQL 中查找从另一个表继承的子表

安装 pg gem 失败,mkmf.rb 找不到 ruby​​ 的头文件(Mac OSX 10.6.5)

在查询中的复合外键/主键列上连接表

SQL数据库表中的多态性?

使用 pg-promise 插入多条记录

null 计算结果为 false 的情况

PostgreSQL 中跨多个表的索引

错误:关系列不存在 PostgreSQL,无法运行插入查询

PostgreSQL:如果不存在则创建表 AS

在 postgres 中导出为 CSV 并使用 GZIP 压缩

Postgres DB 上的整数超出范围

如何使用 postgresql 按计数排序?