根据 window 函数最大值获取其他列,Bigquery

Get Other Columns based on window function maximum value, Bigquery

如何获取 over 子句中的 window 函数给出输出的同一行的整行或其他列值。

例如

with o as (
    select date from unnest(GENERATE_TIMESTAMP_ARRAY('2021-01-01 00:00:00',current_timestamp(),interval 1 hour)) as date
enter code here
), p as (
    select *,RAND()*100 as Number from o
), q as (
    select *,max(number) over(order by date) as best from p
    order by date
)
select * from q

使用上面的查询,我得到的输出是最佳值,它定义了按时间戳排序时高于我的最大数量。

上一栏的输出:

我使用 over 函数计算了最佳值,但我还想要最佳日期的日期列。

也许是这个?

with o as (
    select date from unnest(GENERATE_TIMESTAMP_ARRAY('2021-01-01 00:00:00',current_timestamp(),interval 1 hour)) as date
), p as (
    select *,RAND()*100 as Number from o
), q as (
    select *,max(number) over(order by date) as best from p
)
select * except(date_new_best), max(date_new_best) over (order by date) as date_best 
from (
    select *, if(number=best, date, NULL) as date_new_best
    from q
)
order by date

考虑以下方法

with o as (
    select date from unnest(GENERATE_TIMESTAMP_ARRAY('2021-01-01 00:00:00',current_timestamp(),interval 1 hour)) as date
), p as (
    select *,RAND()*100 as Number from o
), q as (
    select *,max(number) over(order by date) as best from p
)
select * except(best_date),
  last_value(best_date ignore nulls) over(order by date) as best_date
from (
  select *, if(best = lag(best) over(order by date), null, date) best_date
  from q
)   

输出如下