Postgres 在 select 期间将数据类型更改为语句

Postgres change datatype during select into statement

运行 带有 postgis 扩展的 postgres:试图在 select 期间将列的数据类型更改为 table 语句

munsummary table 中的列 sum_popint 是双精度的,我想在 select 语句期间将其更改为整数列。我知道我可以使用 update/alter 语句在 select into 语句之前或之后将列数据类型更改为整数,但我想在 select 语句中进行。

SELECT county,
       SUM(sum_popint) AS residentialpopulation,
       st_union(geom)
INTO countysummary
FROM munsummary
GROUP BY county;

您要做的是 CAST 将其转换为整数。这采用 CAST ( expression AS type );

的形式

所以在你的 SELECT 中,尝试:

SELECT county,
       CAST(SUM(sum_popint) as INTEGER) AS residentialpopulation,
       st_union(geom)
INTO countysummary
FROM munsummary
GROUP BY county;

您也可以使用 shorthand 语法 SUM(sum_popint)::int :

SELECT county,
   SUM(sum_popint)::int AS residentialpopulation,
   st_union(geom)
INTO countysummary
FROM munsummary
GROUP BY county