简体   繁体   English

按ID,日期和最后x天的最大值

[英]Max value by ID, date and last x days

Supposed I have a table : 假设我有一张桌子:

 ---------------
 id |  date | value
------------------
  1 |  Jan 1 | 10
  1 |  Jan 2 | 12
  1 |  Jan 3 | 11
  2 |  Jan 4 | 11

I need to get the max and median value of each id, each date, each for the past 90 days. 我需要获取每个id的最大值和中值,每个日期,每个日期,过去90天。 Im using query : 我使用查询:

select id, date, value
max(value) over (partition by id, date) as max_date,
median(value) over (partition by id, date) as med_date
from table
where date > date - interval '90 days'

I tried to export the data and check manually but the result is not correct. 我试图导出数据并手动检查但结果不正确。 Any thing I missed? 我错过了什么? thanks 谢谢

expected output is to get maximum value of since the last 90 days. 预期产出是获得自过去90天以来的最大值。 for example the date is April 5th, then it will find the maximum value from Jan 5th (the last 90 days) until April 5th. 例如,日期是4月5日,那么它将从1月5日(最近90天)到4月5日找到最大值。 and then the date moves to April 6th, then it will do again for jan 6th until April 6h and so on for each ID 然后日期将移至4月6日,然后它将再次执行1月6日到4月6日,依此类推每个ID

So im assuming u can get several values for same ID and Date and right ? 所以我假设您可以获得相同ID和日期的几个值,对吗? otherwise partitioning for both id and date makes no sense 否则对id和date进行分区是没有意义的

SELECT id, date, max(value), avg(value) from table where date > date - interval '90 days'
group by id, value

'group by' does the partitioning 'group by'进行分区

Why are you using window functions? 你为什么使用窗口函数? This seems to do what you describe: 这似乎做你所描述的:

select id,
       max(value) as max_date,
       percentile_disc(0.5) within group (order by value) as median_value
from table
where date > date - interval '90 days';

If you want this per date , use window functions: 如果您希望每个日期 ,请使用窗口函数:

select t.*
from (select t.*,
             max(value) over (order by date range between '89 day' preceding and current row) as running_max_value,
             percentile_disc(0.5) within group (order by value) range between '89 day' preceding and current row) as running_median_value
      from t
     ) t
where date > date - interval '90 days';

The filter is in the outer query so the preceding period can go back further in time. 过滤器位于外部查询中,因此前一个时段可以进一步追溯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM