我有一个表格如下:
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/