[英]How to get Name of an item corresponding to Min and Max value in a grouped set into different columns
[英]How to add corresponding date to grouped max/min-value in postgres?
我有一个气候时间序列表,其中某些年份的许多台站的测量参数不同(每日值)。 我正在使用pgadmin的postgres 9.4。
该表如下所示:
表名称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
给出每个站点的最高温度值: 表
现在的问题是:如何为每个T_max值添加另一列中的对应日期(测量最大值的日期)?
谢谢你的帮助
您使用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
只需将*
更改为所需的字段名称
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.