2016-01-13 40 views
0

我有一個氣候時間序列表,其中有些年份的許多電臺的測量參數不同(日常數值)。我用pgadmin使用postgres 9.4。如何在postgres中添加相應的日期到分組最大/最小值?

表看起來是這樣的:

表名KL

station_id [int], 
date [date], 
temperature [numeric] ... 

我選擇代碼:

select 
    stat_id, 
    max(temperatur) as "T_max" 
from kl 
group by stat_id 
order by stat_id 

給出了各站最高溫值:table

現在的問題是:如何爲每個T_max值添加另一列(測量該最大值的日期)的相應日期?

感謝您的幫助

+0

如果可能,那麼你可以寫你想要的結果,這將是有益的。 –

回答

0

您使用row_number()得到整排

PARTITION BY重置每個站行計數器,這樣你就不會需要group by

WITH cte as ( 
    SELECT *, 
      ROW_NUMBER() OVER (PARTITION BY station_id 
           ORDER BY temperature DESC) AS rn 
    FROM kl 
) 
SELECT * 
FROM cte 
WHERE rn = 1 

而只是改變*您需要

0
select distinct on (stat_id) 
    stat_id, temperatur, date 
from kl 
order by stat_id, temperatur desc 

使用date列(壞名)字段名解開:

order by stat_id, temperatur desc, date 

http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

如果你想在相同的查詢中最小和最大溫度y:

with kl (stat_id, temperatur, date) as (values 
    (1, 17.1, '2015-01-01'::date), (1, 17.2, '2015-01-02') 
) 
select stat_id, 
    t_max[1]::numeric as t_max, 
    (date 'epoch' + t_max[2] * interval '1 second')::date as d_max, 
    t_min[1]::numeric as t_min, 
    (date 'epoch' + t_min[2] * interval '1 second')::date as d_min 
from (
    select 
     stat_id, 
     max(array[temperatur, extract(epoch from date)::numeric]) as t_max, 
     min(array[temperatur, extract(epoch from date)::numeric]) as t_min 
    from kl 
    group by 1 
) s 
; 
stat_id | t_max | d_max | t_min | d_min  
---------+-------+------------+-------+------------ 
     1 | 17.2 | 2015-01-02 | 17.1 | 2015-01-01 
+0

感謝您的快速回答。這兩種方式都適用於所描述的問題。 –

0

感謝您的快速解答。所有的方法都適用於所描述的問題。但是,我怎樣才能處理這樣的情況,即一個站的測量值會與最大值具有完全相同的值?所以我想列出所有的日期,在一個臺站上達到最大值。

相關問題