PostgreSQL:使用别名列进行case when语句

4
我希望能做类似以下的事情:
select 
case when (select count(*) as score from users t1 )   >5   THEN score   else 0 end 

当我尝试时,出现错误:
column score doesn't exists. 

我可以用其他方法吗?我需要设置一个LIMIT值。当然,我希望以这种方式完成:

select 
case when (select count(*) as score from users t1 )   >5   THEN (select count(*) as score from users)    else 0 end 

但是我需要执行两次相同的查询,你有什么想法吗?


关于常用表达式怎么样?它可以帮助你。 - Martin Strejc
1个回答

8

您可以使用 WITH 子句:

with a as (select count(*) score from t)
select case when score > 5 then score else 0 end from a;

或者子查询(内联视图):

select case when score > 5 then score else 0 end 
from (select count(*) score from t) t;

1
文档链接:WITH 查询(公共表达式) - IMSoP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接