2013-06-23 43 views
0

的时候我就喜欢做这样的事情:PostgreSQL的:情况下使用别名列

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 

但比我需要执行两次这个相同的查询。 有人想法?

+0

什么公共表表达式?它可以帮助你。 –

回答

4

您可以使用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

文档链接:[WITHQUERY(Common Table Expressions)](http://www.postgresql.org/docs/current/static/queries-with.html) – IMSoP

相关问题