簡體   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