【问题标题】:Get Other Columns based on window function maximum value, Bigquery根据窗口函数最大值获取其他列,Bigquery
【发布时间】:2021-11-25 18:35:14
【问题描述】:

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

例如

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 函数计算了最佳值,但我还想要日期列在哪一天最好。

【问题讨论】:

  • 我了解,您需要另一列 best_date 例如 (2021-01-01 21:00:00 UTC)?

标签: sql google-bigquery max window-functions


【解决方案1】:

也许是这个?

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

【讨论】:

    【解决方案2】:

    考虑以下方法

    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
    )   
    

    输出如下

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2021-09-27
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多