在带有差分列的postgres中创建视图

问题描述

我有一个唯一的表,在同一列中包含用于人员和组织的混合数据,只有一个只有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 |            |           | 

我认为这对我来说应该很简单,但我被困住了。

解决方法

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...