2016-11-21 74 views
0

我有問題試圖使用聚合函數結果作爲條件。基本上,我需要選擇具有行「查看次數」超過3個。這裏是代碼的工作:作爲條件的聚合函數

SELECT b.BranchNo AS "Branch Number", 
p.PropertyNo || ', ' || p.PostCode || ', ' || p.City || ', ' || p.Street AS "Object address" , count(v.ViewDate) as "View count" 
FROM Branch b INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo 
INNER JOIN Viewing v ON p.PropertyNo=v.ViewPropertyNo WHERE v.ViewDate>='2014-01-01' 
GROUP BY b.BranchNo, p.PropertyNo; 

我試圖用類似的東西:

HAVING count(v.ViewDate)>=3 

但是,這顯然沒沒有工作。沒有使用子查詢來製造這種情況的方法嗎?

+3

'但這顯然沒有工作......呃,爲什麼沒有工作? – Lamak

+0

正如我所知,HAVING子句必須使用GROUP BY或默認情況下使用當前表獲取組。是的,那不僅僅是執行... – Glebzex

+0

爲什麼不能爲你工作?你在哪裏試圖把HAVING子句放在你的查詢中? –

回答

0

看起來您的select中的字段與group by不匹配,但除此之外,「基於聚合的條件」正是having子句的用途。例如,此查詢應該有效:

SELECT 
b.BranchNo AS "Branch Number", 
p.PropertyNo || ', ' || p.PostCode || ', ' || p.City || ', ' || p.Street AS "Object address" , 
count(v.ViewDate) as "View count" 
FROM Branch b INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo 
INNER JOIN Viewing v ON p.PropertyNo=v.ViewPropertyNo WHERE v.ViewDate>='2014-01-01' 
GROUP BY b.BranchNo, p.PropertyNo, p.PostCode, p.City, p.Street 
HAVING count(v.ViewDate) >= 3; 
0

您需要在查看錶子查詢中進行分組以獲取計數。然後加入。

SELECT b.BranchNo AS [Branch Number], 
    p.PropertyNo + ', ' + p.PostCode + ', ' + p.City + ', ' + p.Street AS [Object address], 
    v.ViewCount 

FROM Branch b 
    INNER JOIN PropertyForRent p ON b.BranchNo=p.PropertyBranchNo 
    INNER JOIN (SELECT ViewPropertyNo, COUNT(*) as ViewCount 
       FROM Viewing 
       WHERE v.ViewDate>='2014-01-01' 
       GROUP BY ViewPropertyNo 
       ) AS v ON p.PropertyNo = v.ViewPropertyNo 
WHERE v.ViewCount >= 3;