3

我有以下表结构,每天每小时的数据:

time_of_ocurrence(timestamp); particles(numeric)

"2012-11-01 00:30:00";191.3
"2012-11-01 01:30:00";46
 ...
"2013-01-01 02:30:00";319.6

如何选择DAILY 最大值和该最大值出现的 HOUR?我试过了

SELECT date_trunc('hour', time_of_ocurrence) as hora,
MAX(particles)
from my_table WHERE time_of_ocurrence > '2013-09-01'
GROUP BY hora ORDER BY hora

但它不起作用:

"2013-09-01 00:00:00";34.35
"2013-09-01 01:00:00";33.13
"2013-09-01 02:00:00";33.09
"2013-09-01 03:00:00";28.08

我的结果将采用这种格式(每天最多一个,显示小时)

"2013-09-01 05:00:00";100.35
"2013-09-02 03:30:00";80.13

我怎样才能做到这一点?谢谢!

4

2 回答 2

3

这类问题经常出现在 StackOverflow 上,如果您想查看其他解决方案,这些问题将被归类

编辑:我将以下代码更改为按天而不是按小时分组。

这是一个解决方案:

SELECT t.*
FROM (
  SELECT date_trunc('day', time_of_ocurrence) as hora, MAX(particles) AS particles
  FROM my_table
  GROUP BY hora
) AS _max
INNER JOIN my_table AS t 
  ON _max.hora = date_trunc('day', t.time_of_ocurrence)
  AND _max.particles = t.particles
WHERE time_of_ocurrence > '2013-09-01'
ORDER BY time_of_ocurrence;

如果不止一行具有最大值,这也可能每天显示多个结果。

使用不显示此类重复的窗口函数的另一种解决方案:

SELECT * FROM (
  SELECT *, 
    ROW_NUMBER() OVER (PARTITION BY date_trunc('day', time_of_ocurrence) 
        ORDER BY particles DESC) AS _rn
  FROM my_table
) AS _max
WHERE _rn = 1
ORDER BY time_of_ocurrence;

如果多行具有相同的最大值,那么一行仍然被编号为第 1 行。如果您需要具体控制哪一行编号为 1,则需要在分区子句中使用 ORDER BY 并使用唯一列来打破这种联系。

于 2013-10-01T15:52:56.243 回答
2

使用窗口函数

select distinct
  date_trunc('day',time_of_ocurrence) as day,
  max(particles) over (partition by date_trunc('day',time_of_ocurrence)) as particles_max_of_day,
  first_value(date_trunc('hour',time_of_ocurrence)) over (partition by date_trunc('day',time_of_ocurrence) order by particles desc)
from my_table
order by 1

这里的一个极端情况是,如果相同的最大数量的粒子出现在同一天,但在不同的时间。这个版本会随机选择其中一个。如果您更喜欢其中一个(例如总是较早的那个),您可以将其添加到 order by 子句中:

      first_value(date_trunc('hour',time_of_ocurrence)) over (partition by date_trunc('day',time_of_ocurrence) order by particles desc, time_of_ocurrence)
于 2013-10-01T15:32:11.573 回答