![](/img/trans.png)
[英]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.