2013-06-23 45 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

相關問題