在sql中使用Group by

时间:2017-11-30 18:04:47

标签: sql

我有一个precipitation_full表,并且有以下架构

    station_id
    day
    precipitation

现在我想得到station_id平均降水量> 75与group by。我在jupyter中使用了这段代码,但结果不正确:

select station_id 
from precipitation_full 
group by station_id  
having avg(precipitation) > 75

如何使用Group by和嵌套查询执行此操作?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT station_id, AVG(precipitation)
FROM precipitation_full
GROUP BY station_id
HAVING AVG(precipitation)>75

答案 1 :(得分:1)

James5'回答看起来是正确的。但是如果你想要所有行(不仅仅是唯一的station_ids),请使用:

;with _intermediate as (
    select
        *,
        avg(precipitation) over (partition by station_id) as AveragePrecipitation
    from precipitation_full
)
select
    station_id,
    [day],
    precipitation
from _intermediate
where
    AveragePrecipitation > 75

在我的回答中,我假设您使用Sql Server

答案 2 :(得分:0)

你在找这样的东西吗?

SELECT *
FROM precipitation_full 
WHERE station_id IN (
        SELECT station_id 
        FROM precipitation_full 
        GROUP BY station_id  
        HAVING AVG(precipitation) > 75
    )