I have a climate timeseries table with different measured parameters for many stations over some years (daily values). I am using postgres 9.4 with pgadmin.
The table looks this way:
Table name kl
station_id [int],
date [date],
temperature [numeric] ...
my select Code:
select
stat_id,
max(temperatur) as "T_max"
from kl
group by stat_id
order by stat_id
gives out the max-temperature value for every station: table
Now the question: how to add for every T_max value the corresponding date in another column (the date on which that max value was measured)?
thanks for your help
You use row_number() to get the whole row
PARTITION BY
reset the row counter for each station, so you wont need 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
And just change *
for the field names you need
select distinct on (stat_id)
stat_id, temperatur, date
from kl
order by stat_id, temperatur desc
Use the date
column (bad name) to untie:
order by stat_id, temperatur desc, date
http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
If you want both the min and max temperatures in the same query:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.