有没有办法通过多个分组找到最高值

Is there a way finding highest value by more than one grouping

我试图找到将两列组合在一起的最大值。 给定一个月,我试图找到一天中最繁忙的时间。

SELECT 
date_part('day', tpep_pickup_datetime) AS trip_day,
date_part('hour', tpep_pickup_datetime) AS trip_hour,
count(*) AS numbers
FROM nyc_yellow_2019_01
GROUP BY trip_day, trip_hour
ORDER BY trip_day, count(*) desc)

这列出了每天的所有时间,但我只想要每天最重要的时间。

我还尝试创建一个视图 table,然后我写道:

SELECT DISTINCT(trip_day) MAX(numbers)
FROM busy_hour
GROUP BY trip_day;

这很接近,但不会告诉我确切的时间。

最后我在最后一个查询中尝试了 where 子句:

SELECT trip_hour
FROM busy_hour
WHERE
(SELECT DISTINCT(trip_day) MAX(numbers)
FROM busy_hour
GROUP BY trip_day);

这给了我一个错误,指出子查询只能返回一列。

任何帮助将不胜感激

您似乎在使用 Postgres,正如使用 date_part() 所表明的那样。

如果是这样,你可以使用distinct on:

select distinct on (trip_day)
    date_part('day', tpep_pickup_datetime) as trip_day,
    date_part('hour', tpep_pickup_datetime) as trip_hour,
    count(*) as numbers
from nyc_yellow_2019_01
group by trip_day, trip_hour
order by trip_day, numbers desc

I am trying to find the busiest hour in a day, given a month.

如果您想要每天最忙的时间,请使用 window 函数:

SELECT th.*
FROM (SELECT date_part('day', tpep_pickup_datetime) AS trip_day,
             date_part('hour', tpep_pickup_datetime) AS trip_hour,
             count(*) AS numbers,
             row_number() over (partition by date_part('day', tpep_pickup_datetime) order by count(*) desc) as seqnum
      FROM nyc_yellow_2019_01
      GROUP BY trip_day, trip_hour
     ) th
WHERE seqnum = 1;