[英]Get the Date where the min max value is at when querying with between
Is there a way to get the day when the Min and Max value occurred when querying between certain dates.有没有办法在某些日期之间查询时获取最小值和最大值发生的日期。
Lets say i'm querying between 1st of the month to 31st and i want to see on which day the min and max value for that given column occured.假设我在本月 1 日到 31 日之间进行查询,我想查看该给定列的最小值和最大值发生在哪一天。
You can use window functions and aggregation:您可以使用 window 函数和聚合:
select max(case when seqnum_asc = 1 then col end) as min_val_date,
max(case when seqnum_desc = 1 then col end) as max_val_date
from (select t.*,
row_number() over (order by col asc) as seqnum_asc,
row_number() over (order by col desc) as seqnum_desc
from t
where datecol >= ? and datecol < ?
) t;
Or you can just use aggregation:或者你可以只使用聚合:
select (array_agg(datecol order by col desc limit 1))[ordinal(1)] as max_val_date,
(array_agg(datecol order by col asc limit 1))[ordinal(1)] as min_val_date
from t;
Consider below (if you care of performance)考虑下面(如果你关心性能)
select date_of_min, date_of_max
from (
select date_col as date_of_min from `project.dataset.table`
where date_col between min_date and max_date
order by value_col limit 1
), (
select date_col as date_of_max from `project.dataset.table`
where date_col between min_date and max_date
order by value_col desc limit 1
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.