我是PostgreSQL和本网站的新手。我需要你的帮助。
我需要获得超过平均降雨量的所有月份。
我尝试了这个,但它不起作用,有人可以解释一下吗?
Select month, rain from weather
where rain > avg(rain)
group by month , rain;
非常感谢。
答案 0 :(得分:3)
试试这个
SELECT month FROM (SELECT month, avg(rain) avg_rain FROM weather GROUP BY month) a
CROSS JOIN
(SELECT avg(rain) rain FROM weather) b
WHERE avg_rain > rain
答案 1 :(得分:2)
WITH rain_avg_by_month AS (
SELECT month, AVG(rain) AS rain_avg
FROM weather
GROUP BY month
), total_rain_avg AS (
SELECT AVG(rain_avg)
FROM rain_avg_by_month
)
SELECT month
FROM rain_avg_by_month, total_rain_avg
WHERE rain_avg_by_month.rain_avg > total_rain_avg.avg
;
答案 2 :(得分:0)
select * from (
select
month,
rain,
avg(rain) over() avg_rain
from weather
) t
where rain > avg_rain;
这里我们假设每月有一条记录。第一个查询(嵌套的)给出了所有月份和相应的降雨值以及平均降雨量值(我们对集合中的所有记录使用窗口函数avg
)。然后外部查询给出了我们所需要的:雨量值大于平均降雨量的月份。