2013-10-01 35 views
3

的相應小時,我有以下表結構,日常每小時的數據:PostgreSQL的選擇日常max和ocurrence

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 

我如何選擇最高每日和每小時在這個最大發生? 我試過

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 

我該怎麼做?謝謝!

回答

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使用唯一列來打破這種關係。

+0

謝謝,但這顯示從同一天的幾個'最大'... – Fernando

+0

好吧,我已經試圖修復,在上述編輯。 –

+0

它仍然顯示同一天的價值。我試圖修改它。 – Fernando

2

使用window functions

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 

一個邊緣的情況下在這裏,如果粒子相同的最大數量在同一天出現,但在不同的時間。這個版本會隨機挑選其中的一個。如果你喜歡一個比其他(總是例如較早的企業之一),你可以通過條款添加到訂單:

 first_value(date_trunc('hour',time_of_ocurrence)) over (partition by date_trunc('day',time_of_ocurrence) order by particles desc, time_of_ocurrence) 
+0

這是每天顯示多個結果,我的目標是當天的最大值和發生的小時數。但我認爲你很接近! – Fernando

+0

@Fernando對不起,編輯答案 –

+0

非常感謝! – Fernando