【问题标题】:create a view in postgres with differential columns在 postgres 中创建具有差异列的视图
【发布时间】:2020-12-22 04:30:33
【问题描述】:

我有一个独特的表,其中包含同一列中的人员和组织混合的数据,只有一个只有 1 个字母的字段设置数据引用。

例子

id|type | surname of person/organization | name of person/address of organization | person sex/organization fiscal code
 1|   P | GATES                          | BILL                                   | M
 2|   O | GOOGLE                         | PALO ALTO                              | 04340349204920
 3|   P | DOE                            | JENNIFER                               | F
...etc....

我想在 Postgres 中创建一个按引用类型(字母)组织和分隔信息的视图,像这样

id|type|surname|name      |sex|organization|address    |fiscal code
 1| P  | GATES | BILL     | M |            |           |         
 2| O  |       |          |   | GOOGLE     | PALO ALTO | 04340349204920
 3| P  | DOE   | JENNIFER | F |            |           | 

我认为这应该很简单(对我来说),但我卡住了。

【问题讨论】:

    标签: sql postgresql case sql-view


    【解决方案1】:

    您可以使用大小写表达式:

    create view myview (surname, name, sex, orga, address, fiscal_code) as
    select
        id,
        type,
        case when type = 'P' then surname_or_orga    end as surname,
        case when type = 'P' then name_or_address    end as name,
        case when type = 'P' then sex_or_fiscal_code end as sex,
        case when type = 'O' then surname_or_orga    end as orga,
        case when type = 'O' then name_or_address    end as address,
        case when type = 'O' then sex_or_fiscal_code end as fiscal_code
    from mytable
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2020-07-10
      • 2012-01-22
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多