繁体   English   中英

使用 between 查询时获取最小值最大值所在的日期

[英]Get the Date where the min max value is at when querying with between

有没有办法在某些日期之间查询时获取最小值和最大值发生的日期。

假设我在本月 1 日到 31 日之间进行查询,我想查看该给定列的最小值和最大值发生在哪一天。

您可以使用 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;

或者你可以只使用聚合:

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;
   

考虑下面(如果你关心性能)

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.

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