【问题标题】:postgresql : create table as union select with a serial keypostgresql:使用序列键创建表作为联合选择
【发布时间】:2020-12-17 04:07:47
【问题描述】:

我正在尝试从 raw_data 表创建维度表 dim_airport。原始表有 2 个机场代码列(出发地和目的地)。我想获得所有机场代码的详尽独特的集合并用它创建一个表。另外,我还需要添加一个序列号来执行自动递增。我可以这样做 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 窗口函数,它就可以工作。我正在寻找一种解决方案,它可以直接自动递增,而无需明确定义 row_number() 中的值

【问题讨论】:

    标签: postgresql create-table


    【解决方案1】:

    “Create table ... As ...”的语法不允许定义额外的列,它从 select 语句中定义 only 列。当然,您可以通过选择将常量作为占位符并建立列名来坚持。然后创建一个序列,更新表以设置占位符的值,然后创建几个更改表以完成所需的定义。
    一个更简单的方法只是一个两步过程:

    1. 创建表。
    2. 用简单的选择填充。
    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 ;  
    

    您不需要 DISTINCT 在任一选择上,因为 UNION 本身会消除重复项。 见examples here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多