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
如果可能,那麼你可以寫你想要的結果,這將是有益的。 –