我有一张桌子,如下:
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
新表,在其中将重复的time
行合并为总交易量和交易量加权平均价格。
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)
的结果强制转换为整数,但这也不起作用。
问题
如何强制字段为integer
类型?
答案 0 :(得分:3)
SUM将数字的数据类型更改为较大的值,因此不会累加溢出的数字:
bigint用于smallint或int参数,数字用于bigint参数,否则与参数数据类型相同
答案 1 :(得分:0)
是的。像这样用sum(volume):: integer将其转换为整数:
SELECT
time,
SUM(volume)::integer AS volume,
here
SUM(volume * price) / SUM(volume) AS price
INTO
foo
FROM
foo_raw
GROUP BY
time
ORDER BY
time;
如果您真正关心结果集的数据类型,我将适当地转换每一列。