sql - 编写查询的更好方法

标签 sql postgresql join view

我在连接表和 View 后创建 View 。 该 View 包含连接中的一些实际列,其中一些是计算列(我们称它们为 type1)。其中一些是计算列(type2)的计算。 有什么方法可以引用 type1 列来仅通过它们的名称来计算 type2 而不是再次编写整个代码? (我也不想创建另一个子查询),只是检查是否有任何有效的方法来编写代码。不在这里发布实际代码,这是我正在尝试做的简短形式:

    Create view ABCD 
     col1,col2 , calc_col1, calc_col2 , Calc_col3
   as 
     select a.col1 as col1 ,
            a.col2 as col2,
            case when  some_calulations then 2 else 0  end as calc_col1,
           ( case when  some_calulations then 2 else 0  end) - a.somecol as calc_col2 ,
      ( ( case when  some_calulations then 2 else 0  end) - a.somecol ) + 5 )as calc_col3 
 from Table1 as a
   left join view2 as b
   on join_condition

最佳答案

使用lateral subqueries

select
    a.col1 as col1,
    a.col2 as col2,
    c.calc_col1,
    d.calc_col2,
    d.calc_col2 + 5 as calc_col3 
from
    Table1 a
    left join
    view2 b on join_condition
    cross join lateral
    (select case when some_calulations then 2 else 0 end as calc_col1) c
    cross join lateral
    (select calc_col1 - a.somecol as calc_col2) d

关于sql - 编写查询的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281722/

相关文章:

java - Android - 将解析的 xml 数据存储到 sql 时出错

MySQL 检查结果是否被收藏

sql-server - 选择由另一个表中的另一列命名的列

MySQL 多对一连接。如何找到最差(最低)结果和最新结果?

SQLite 找不到避免笛卡尔积的方法

mysql - 查找给定坐标的特定半径内的所有位置的查询

java - "NULL not allowed for column ' id '"即使日志说它有值绑定(bind)

PostgreSQL - 通过 pgAdmin UI 创建一个新的数据库

javascript - 在 Node.js 中上传和检索图像?

mysql - 这是好的数据库规范化吗?