我在尝试使用聚合函数结果作为条件时遇到问题。基本上,我需要选择具有"查看计数"的行。超过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
但这显然不起作用。有没有办法在不使用子查询的情况下制作这种条件?
答案 0 :(得分: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;
答案 1 :(得分: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;