首页 > 解决方案 > 从子查询中保存价值并在以后重用它?

问题描述

如何多次使用子查询的结果?有没有办法命名该结果并在其他地方使用它?我知道 xyz as ... 这似乎不起作用?

我找到了这个并想要更具体的东西?

损坏代码示例:

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;

标签: postgresql

解决方案


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

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的信息


推荐阅读