2016-01-29 80 views
0

所以,我有這個小SQL查詢搜索時的列不存在:PostgreSQL的:在WHERE子句

SELECT 
    COUNT(distinct (customerid)) AS cs, prod_id 
FROM 
(orderlines JOIN orders ON (orderlines.orderid=orders.orderid)) AS table_1 
WHERE table_1.cs= 1 
GROUP BY table_1.prod_id 
ORDER BY cs ASC 

什麼,這是應該做的,就是算上不同客戶ID的和返回表僅包含僅有不同的條目customerid

當我執行此我得到以下錯誤:

ERROR: column table_1.cs does not exist 
LINE 6: WHERE table_1.cs= 1 
     ^
*********Error********** 

ERROR: column table_1.cs does not exist 
SQL state: 42703 
Character: 156 

它聲稱,列CS沒有的時候我已經清楚這裏定義它存在:

SELECT 
     COUNT(distinct (customerid)) AS cs, prod_id 
+1

您過濾與having子句GROUP彙總結果BY .. HAVING COUNT(不同(customerid))= 1 – Mihai

回答

0

你可以用」在WHERE子句中引用在選擇列表中定義的別名。您可以使用HAVING子句或使用選擇子..

隨着子選擇,你可以安排是這樣的:

SELECT * FROM (
SELECT 
    COUNT(distinct (customerid)) AS cs, prod_id 
FROM 
(orderlines JOIN orders ON (orderlines.orderid=orders.orderid)) 
GROUP BY table_1.prod_id) AS table_1 
WHERE cs= 1 
ORDER BY cs ASC