如何将聚合函数应用于单个查询中其他聚合函数的结果?

How to apply aggregate functions to results of other aggregate functions in single query?

我有一个 table BIKE_TABLE 包含列 Rented_Bike_CountHourSeason。我的目标是确定每个季节的平均小时租金数,以及每个季节的平均小时租金数 MINMAXSTDDEV。我需要在单个查询中执行此操作。

我用过:

SELECT 
    SEASONS,
    HOUR,
    ROUND(AVG(RENTED_BIKE_COUNT),2) AS AVG_RENTALS_PER_HR
FROM TABLE
GROUP BY HOUR, SEASONS
ORDER BY SEASONS

这让我很接近,return96 行(4 季 x 每 24 小时),例如:

SEASON HOUR AVG_RENTALS_PER_HR
Autumn 0 709.44
Autumn 1 552.5
Autumn 2 377.48
Autumn 3 256.55

但我不知道如何 return 以下使用 ROUND(AVG(RENTED_BIKE_COUNT) 作为基础的结果:

  1. 每个季节的平均每小时租金是多少?答案应该是四行,例如:Autumn, [avg.每小时租用的自行车数量]
  2. 每个季节的平均每小时租金数 MIN 是多少?
  3. MAX
  4. 也一样
  5. STDDEV 相同。

我试过了运行

MIN(AVG(RENTED_BIKE_COUNT)) AS MIN_AVG_HRLY_RENTALS_BY_SEASON,
MAX(AVG(RENTED_BIKE_COUNT)) AS MAX_AVG_HRLY_RENTALS_BY_SEASON,
STDDEV(AVG(RENTED_BIKE_COUNT)) AS STNDRD_DEV_AVG_HRLY_RENTALS_BY_SEASON

嵌套 SELECT 然后嵌套 FROM 子句,但我似乎无法正确处理。我很接近吗?非常感谢任何帮助。

我认为你把任务复杂化了。这会给你答案吗?如果不是请告诉我它的输出和你想要的输出之间的区别。
当然,您可以添加 ROUND() 以达到您认为合适的列等。

SELECT 
    SEASONS,
    MIN(RENTED_BIKE_COUNT) minimum,
    MAX(RENTED_BIKE_COUNT) maximum,
    STDDEV(RENTED_BIKE_COUNT) sDev,
    AVG(RENTED_BIKE_COUNT) average
FROM TABLE
GROUP BY SEASONS
ORDER BY SEASONS;

根据您的评论看来您可能需要以下查询。

WITH seasons AS(
  SELECT 
    Season,
    AVG(RENTED_BIKE_COUNT) seasonAverage
  FROM TABLE
  GROUP BY season)
SELECT
  AVG(seasonAverage) average,
  MIN(seasonAverage) minimum,
  MAX(seasonAverage) maximum,
  STDDEV(seasonAverage) sDev
FROM
  seasons;