在具有差异列的 postgres 中创建视图
create a view in postgres with differential columns
我有一个独特的 table 包含同一列中的人员和组织的混合数据,只有一个字段只有 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 | | |
我认为这应该很简单(对我来说),但我卡住了。
您可以使用 case 表达式:
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
我有一个独特的 table 包含同一列中的人员和组织的混合数据,只有一个字段只有 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 | | |
我认为这应该很简单(对我来说),但我卡住了。
您可以使用 case 表达式:
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