我有一个气候时间表,其中包含多年来许多站点的不同测量参数(每日值)。我正在使用postgres 9.4和pgadmin。
表格看起来像这样:
表名 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
只需更改*
以获取您需要的字段名称
答案 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
如果您想要同一查询中的最低和最高温度:
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
答案 2 :(得分:0)
感谢您的快速解答。所有方法都适用于所描述的问题。但是,如何处理一个工作站的测量值与最大值具有完全相同值的情况呢?所以我想列出所有日期,在一个电台上达到最大值。