这里是新的 sql 用户,我正在尝试对
postgresql
中实现的现有视图进行更改。该视图计算一个列,computed_column
,它是一个函数 2 个变量(我将在第一个片段中将其称为 #1 和 #2),它可以从现有的列中派生出来,我不确定它是什么做到这一点的最佳方法是不要在 computed_column
选择中做大量案例工作。
视图如下:
create or replace view my_view as
select
-- some other columns not included here
(case when t.flag = 'on' THEN (#1) ELSE #2 END) / (#1 - #2) as computed_column
from table1 t1
left join table2 t2 on ....
left join table2 t3 on ....
我尝试了这样的事情(请注意,
derived_column1
是上面的#1,同样是#2)
create or replace view my_view as
select
-- some other columns not included here
(case when t1.proto = 'p' then t2.c2 else t2.c3) as derived_column1,
(case when t1.proto = 's' then t2.c4 else t2.c5) as derived_column2,
(case when t1.flag = 'on' then (derived_column1) ELSE derived_column2 END) / (derived_column1 - derived_column2) as computed_column
from table1 t1
left join table2 t2 on ....
left join table2 t3 on ....
但这不起作用,因为我显然无法引用同一 select 子句中定义的列别名,所以我决定做一个子查询,但它似乎相当冗长,因为我有一长串列被选中,我必须将其放入外部选择和内部子查询选择中。有更好的方法吗?
尝试使用子查询
create or replace view my_view as
select *
(case when t1.flag = 'on' then (derived_column1) ELSE derived_column2 END) / (derived_column1 - derived_column2) as computed_column
from(
select
-- some other columns not included here
(case when t1.proto = 'p' then t2.c2 else t2.c3) as derived_column1,
(case when t1.proto = 's' then t2.c4 else t2.c5) as derived_column2,
from table1 t1
)t1
left join table2 t2 on ....
left join table2 t3 on ....