postgresql : create table as union select with a serial key
postgresql : create table as union select with a serial key
我正在尝试从 raw_data dim_airport 创建一个维度 table dim_airport table。原始 table 有 2 个机场代码列(起点和终点)。我想获得一组详尽的所有机场代码,并用它创建一个 table。此外,我还需要添加一个序列号密钥来执行自增。我可以做到这一点 row_number 但想找到另一种方法来做到这一点。
create table DIM_airport (airportkey serial primary key )
as
select distinct originairportcode as airportcode,
origairportname as airportname,
origincityname as city from raw_data
union
select distinct destairportcode, destairportname, destcityname
from raw_data;
如果我在 airportcode 上定义了一个 row_number window 函数,它就可以工作。我正在寻找一种解决方案,它可以直接自动递增而无需明确定义 row_number()
的值
“Create table ... As ...”的语法不允许定义额外的列,它只定义 select 中的 列] 陈述。当然,您可以通过 select 将常量作为占位符并建立列名来坚持。然后创建一个序列,更新 table 以设置占位符的值,然后进行一些更改 table 以完成所需的定义。
一个简单得多的方法就是一个两步过程:
- 创建 table.
- 使用简单的 select.
填充
create table DIM_airport( airportkey integer generated always as identity
, airportcode text
, airportname text
, city text
, constraint DIM_airport_pk
primary key (airportkey)
) ;
insert into DIM_airport(airportcode, airportname, city)
select originairportcode
, origairportname
, origincityname
union
select destairportcode
, destairportname
, destcityname ;
您不需要在 select 上使用 DISTINCT,因为 UNION 本身会消除重复项。
参见 examples here。
我正在尝试从 raw_data dim_airport 创建一个维度 table dim_airport table。原始 table 有 2 个机场代码列(起点和终点)。我想获得一组详尽的所有机场代码,并用它创建一个 table。此外,我还需要添加一个序列号密钥来执行自增。我可以做到这一点 row_number 但想找到另一种方法来做到这一点。
create table DIM_airport (airportkey serial primary key )
as
select distinct originairportcode as airportcode,
origairportname as airportname,
origincityname as city from raw_data
union
select distinct destairportcode, destairportname, destcityname
from raw_data;
如果我在 airportcode 上定义了一个 row_number window 函数,它就可以工作。我正在寻找一种解决方案,它可以直接自动递增而无需明确定义 row_number()
的值“Create table ... As ...”的语法不允许定义额外的列,它只定义 select 中的 列] 陈述。当然,您可以通过 select 将常量作为占位符并建立列名来坚持。然后创建一个序列,更新 table 以设置占位符的值,然后进行一些更改 table 以完成所需的定义。
一个简单得多的方法就是一个两步过程:
- 创建 table.
- 使用简单的 select. 填充
create table DIM_airport( airportkey integer generated always as identity
, airportcode text
, airportname text
, city text
, constraint DIM_airport_pk
primary key (airportkey)
) ;
insert into DIM_airport(airportcode, airportname, city)
select originairportcode
, origairportname
, origincityname
union
select destairportcode
, destairportname
, destcityname ;
您不需要在 select 上使用 DISTINCT,因为 UNION 本身会消除重复项。 参见 examples here。