2013-11-20 26 views
1

我想要顯示的值只有當總和高於2和SQL和直接條件

奇怪的輸出

select 1+3 > 2; 
?column? 
---------- 
t 
(1 register) 

ERROR: column "val" does not exist 
line 1: select 1+3 as val where val > 2; 
           ^

ERROR: syntax error at or near "CASE" 
line 1: select 1+3 as val CASE val > 2; 
         ^

是什麼正確的方法?這些似乎都不起作用。

回答

1

您無法使用where條款中的派生列,因此有關於此的許多討論。這樣做的一個方法是使用子查詢或CTE

select val 
from (select 1+3 as val) as v 
where val > 2 

with cte (
    select 1+3 as val 
) 
select val 
from cte 
where val > 2 
1

你需要一個子查詢,因爲SELECT子句中定義的列是不可用在where子句:

select val 
from (select 1+3 as val) as vals 
where val > 2 

的CTE也可以工作:

with vals as (
select 1+3 as val 
) 
select val 
from vals 
where val > 2 
0

你可以簡單地寫,

選擇總和(1 + 3)具有和VAL(1+ 3)> 2

作爲@Denis建議,

select val from (select 1+3 as val) as v where val > 2 
+1

在這裏工作,但做了一個非常非常不同的事情。 –

+0

@Denis我無法理解。除了用戶要求的輸出外,它會產生任何錯誤的答案? – Haji

+0

@DownVoter你能解釋我的查詢有什麼問題嗎? – Haji