[英]Postgres: Get value of a column corresponding to max of other column in a group
我正在嘗試編寫一個 postgres 查詢,它返回組中的最大值、最小值、中值、第一個和最后一個值以及每個聚合值的時間戳列
桌子
Id Timestamp_utc Value
1 2020-11-05 15:36:15.768388 10
1 2020-11-05 15:40:15.768388 20
1 2020-11-05 15:44:15.768388 30
1 2020-11-05 15:45:15.768388. 5
1 2020-11-05 15:59:15.768388 25
1 2020-11-05 16:59:15.768388 25
預期結果
Id Median Median_Timestamp Min Min_Timestamp Max Max_TimeStamp
1 17.5. 15:44:15.768388 5 2020-11-05 15:45:15.768388 30 2020-11-05 15:44:15.768388
我有這個查詢分組數據不包括時間戳
SELECT Id, time_bucket('60', timestamp_utc) AS bucket,
percentile_cont(0.5) within group (order by value) median_value,
min(value) min_value,
max(value) max_value
FROM rs.MyTable
WHERE id IN ( 1111,123)
AND timestamp_utc Between '2020-11-05 10:00:15.748643' and '2020-11-05 16:35:48.750313'
GROUP BY id, bucket
ORDER BY id, bucket
當值最大時,有沒有一種方法可以獲取時間戳列以及聚合值(如 timestamp_utc col 數據)?
一種選擇是在子查詢中使用窗口函數通過遞增和遞減value
對時間戳進行排序,然后在外部查詢中進行條件聚合以帶來相關值。
select id, bucket,
percentile_cont(0.5) within group (order by value) median_value,
min(value) min_value,
max(timestamp_utc) filter(where rn_asc = 1) min_timestamp,
max(value) max_value,
max(timestamp_utc) filter(where rn_desc = 1) max_timestamp
from (
select t.*,
row_number() over(partition by id, bucket order by value) rn_asc,
row_number() over(partition by id, bucket order by value desc) rn_desc
from (
select t.*, time_bucket('60', timestamp_utc) as bucket
from rs.mytable t
where
id in (1111,123)
and timestamp_utc between '2020-11-05 10:00:15.748643'::timestamp
and '2020-11-05 16:35:48.750313'::timestamp
) t
) t
group by id, bucket
order by id, bucket
注意,我們需要先計算bucket,並將其放入窗函數的分區中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.