我使用了一个视图来获得正确的答案,但是我想在一个SQL语句中使用它,我也想知道是否有办法在不重新抛出表格的情况下进行操作。
我可以COUNT(OW_OWNERNO) AS NO_HOUSES
在我的where子句中使用NO_HOUSES
吗?有没有办法定义它。
本声明试图计算数据库中人员拥有的房屋数量,并仅计划拥有多个房屋的人。
CREATE VIEW NUMHOUSE AS
SELECT OW_FIRSTNAME, OW_LASTNAME, **COUNT(OW_OWNERNO) AS NO_HOUSES**
FROM (rentproperty JOIN OWNER ON RP_OW_OWNERNO = OW_OWNERNO)
WHERE RP_TYPE = 'House'
GROUP BY OW_OWNERNO;
SELECT * FROM NUMHOUSE
NO_HOUSES> 1;
答案 0 :(得分:2)
这有两种方法。第一个使用Fabio建议的having子句。
SELECT OW_FIRSTNAME, OW_LASTNAME, COUNT(OW_OWNERNO) AS NO_HOUSES
FROM (rentproperty JOIN OWNER ON RP_OW_OWNERNO = OW_OWNERNO)
WHERE RP_TYPE = 'House'
GROUP BY OW_OWNERNO
having no_houses > 1 -- note some dbs might not let you use an alias here
这个使用子查询
select * from (
SELECT OW_FIRSTNAME, OW_LASTNAME, COUNT(OW_OWNERNO) AS NO_HOUSES
FROM (rentproperty JOIN OWNER ON RP_OW_OWNERNO = OW_OWNERNO)
WHERE RP_TYPE = 'House'
GROUP BY OW_OWNERNO
) temp
where no_houses > 1
他们同样运作良好。
答案 1 :(得分:1)
我认为您应该使用HAVING
代替WHERE
实施例
SELECT * FROM NUMHOUSE HAVING COUNT(NO_HOUSES) > 1;