保存子查询的值并在以后重用?

时间:2019-01-28 11:51:55

标签: postgresql

如何多次使用子查询的结果?有什么办法可以命名结果并在其他地方使用它?我知道xyz为...,但这似乎行不通?

我找到了this,想要更具体的内容吗?

破损代码示例:

with g_surf as (select surface_area from countries where name like 'Germa%')
select abs(surface_area - g_surf) from countries;

使用整个子查询的工作代码:

select abs(surface_area - (select surface_area from
    countries where name like 'Germa%')) from countries;

1 个答案:

答案 0 :(得分:1)

只需将问题标记为已解决:
在您的示例中,g_surf是CTE(通用 Table 表达式),即它充当表格而不是字段。

with g_surf as (select surface_area from countries where name like 'Germa%')
select abs(surface_area) from g_surf; 

当然,如果您的g_surf表中有一个countries字段,则可以编写:

with myCTE as (select surface_area, g_surf from countries where name like 'Germa%')
select abs(surface_area - g_surf) from myCTE;

有关CTE here的更多信息。