SQL 试图求出 1 个属性的平均值
SQL Trying To Find The Average of Just 1 Attribute
在 SQL 中,我试图查找并列出租金高于房屋平均租金的房屋的地址。所以我有一个 PropertyForRent table,其中列出了不同的出租房屋和公寓。这是 table:
relation
到目前为止,我已经编写了完整的 SQL 查询,但我不确定它是否确实按照我的意图执行。
这里是:
SELECT street, city, postcode, type, rent – (SELECT AVG (rent) FROM PropertyForRent WHERE type = ‘House’) AS avgRent
FROM PropertyForRent
WHERE rent >
(SELECT AVG(rent)
FROM PropertyForRent);
这是正确的语法吗?我可以在 SELECT AVG 中使用 WHERE 吗?还是有更好的方法来定义专门针对房屋的租金?我觉得其余的还可以,但我不完全确定。
感谢您的帮助
您可以在 where
子句中使用子查询。但是,我认为您需要过滤有关房屋的数据集,如下所示:
select p.*
from PropertyForRent p
where
p.type = 'House'
and p.rent > (select avg(p1.rent) from PropertyForRent p1 where p1.type = 'Rent')
这可能用 window 函数表示得更简单:
select *
from (
select p.*, avg(rent) over() avg_rent
from propertyForRent p
where type = 'House'
) p
where rent > avg_rent
在 SQL 中,我试图查找并列出租金高于房屋平均租金的房屋的地址。所以我有一个 PropertyForRent table,其中列出了不同的出租房屋和公寓。这是 table:
relation
到目前为止,我已经编写了完整的 SQL 查询,但我不确定它是否确实按照我的意图执行。
这里是:
SELECT street, city, postcode, type, rent – (SELECT AVG (rent) FROM PropertyForRent WHERE type = ‘House’) AS avgRent
FROM PropertyForRent
WHERE rent >
(SELECT AVG(rent)
FROM PropertyForRent);
这是正确的语法吗?我可以在 SELECT AVG 中使用 WHERE 吗?还是有更好的方法来定义专门针对房屋的租金?我觉得其余的还可以,但我不完全确定。
感谢您的帮助
您可以在 where
子句中使用子查询。但是,我认为您需要过滤有关房屋的数据集,如下所示:
select p.*
from PropertyForRent p
where
p.type = 'House'
and p.rent > (select avg(p1.rent) from PropertyForRent p1 where p1.type = 'Rent')
这可能用 window 函数表示得更简单:
select *
from (
select p.*, avg(rent) over() avg_rent
from propertyForRent p
where type = 'House'
) p
where rent > avg_rent