sql - PostgreSQL:SELECT INTO 正在更改字段的数据类型

标签 sql postgresql

我有一个表格如下:

CREATE TABLE IF NOT EXISTS foo_raw
(
    time   TIMESTAMPTZ NOT NULL,
    volume INTEGER,                  <-- note source field is of type integer
    price  DOUBLE PRECISION
);

我从 csv 文件填充它:

COPY foo_raw(time,volume,price) FROM 'raw_data.csv' DELIMITER ',' CSV

然后,我对一个新表进行SELECT INTO操作,将重复的时间行合并为总交易量和交易量加权平均价格。

选择:

SELECT
    time, 
    SUM(volume)::integer AS volume,          <-- note typecast to integer here
    SUM(volume * price) / SUM(volume) AS price
INTO
    foo
FROM
    foo_raw
GROUP BY
    time
ORDER BY
    time;

如果我描述我的新表,我会看到 volume 字段的类型为 numeric,而不是 integer

pg=# \d foo
                   Table "public.foo"
 Column |           Type           | Collation | Nullable | Default 
--------+--------------------------+-----------+----------+---------
 time   | timestamp with time zone |           | not null | 
 volume | numeric                  |           |          |     
 price  | double precision         |           |          | 

类型转换:

您会在上面的 SELECT INTO 语句中注意到,我尝试将 SUM(volume) 的结果类型转换为整数,但这也不起作用。

问题

如何强制字段为整数类型?

最佳答案

SUM将数字的数据类型更改为更大的值,这样加起来就不会导致数字溢出:

bigint for smallint or int arguments, numeric for bigint arguments, otherwise the same as the argument data type

关于sql - PostgreSQL:SELECT INTO 正在更改字段的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044146/

相关文章:

sql - Postgres 跨表唯一组合约束

postgresql - 如何正确使用 Postgres 触发器中的任务队列

PostgreSQL NOT NULL 外键和带序列的默认值

sql - 如何将子表的删除级联到父表?

postgresql - 如何对postgres sql中的不规则字母数字数据进行排序

sql - 在查询中两次使用相同的表别名

php - 如何在 SELECT 语句 mySQL 中做 * 和计算?

mysql - Doctrine2 链式多表连接和过滤

sql - PostgreSQL:获取列的最小值及其相关城市

sql - 将 SQL 结果分组/聚合到 1 小时的桶中