【问题标题】:How do i user windowed function with count(case when...)我如何使用计数的用户窗口函数(情况下......)
【发布时间】:2022-01-14 15:14:18
【问题描述】:

世界!

我有一个第一个“级别”表,看起来像这样:

level id level_date
1 A 2021-12-02
2 A 2021-12-04
3 A 2021-12-08
1 B 2021-12-02
2 B 2021-12-05
3 B 2021-12-09

还有第二张“战斗”桌:

id battle_date
A 2021-12-01
A 2021-12-03
A 2021-12-06
A 2021-12-07
B 2021-12-01
B 2021-12-02
B 2021-12-03

我想要做的是找到平均战斗次数,需要达到每个级别。

当battle_date > level_X-1_date,但是battle_date

所以对于玩家 A,我们有一场战斗可以达到 1 级,一场战斗可以达到 2 级,还有两次战斗可以达到 3 级。 对于玩家 B,我们有一场战斗可以达到 1 级,有两次战斗可以达到 2 级,零战斗可以达到 3 级

结果表应如下所示:

level avg_battle_count
1 1
2 1.5
3 1

我很确定这是一种“差距和孤岛”问题,但我不知道我应该如何构建一个考虑窗口函数来计算级别的 avg(battle_count) 的查询

【问题讨论】:

  • mySql 还是 BogQuery?
  • 只标记您使用的数据库。
  • 通常当 BigQuery 和 mySql 都被标记时 - 它以 BigQuery 结束 :o) 但很高兴确认!

标签: sql google-bigquery gaps-and-islands windowed


【解决方案1】:

我没有尝试过,我认为这应该会产生您正在寻找的结果:

select
  level,
  avg(battle_count) avg_battle_count
from (
  select
    x.level,
    x.id,
    count(*) battle_count
  from level x
  left join level x_1 on 
    x.id = x_1.id and 
    x.level = x_1.level-1
  join battles b on 
    x.id = b.id and 
    b.battle_date < x.level_date and 
    (b.battle_date > x_1.level_date or x_1.level_date is null)
  group by
    x.level,
    x.id
)
group by level
order by level

【讨论】:

    【解决方案2】:

    考虑以下方法(BigQuery)

    select level, avg(battle_count) as avg_battle_count from (
      select level, id, battle_count - ifnull(lag(battle_count) over(partition by id order by level), 0) as battle_count
      from (
        select level, t1.id, count(*) battle_count
        from levels t1 left join battles t2
        on t1.id = t2.id and battle_date < level_date 
        group by level, id
      )
    )
    group by level               
    

    如果应用于您问题中的样本数据

    with levels as (
      select 1 level, 'A' id, '2021-12-02' level_date union all
      select 2, 'A', '2021-12-04' union all
      select 3, 'A', '2021-12-08' union all
      select 1, 'B', '2021-12-02' union all
      select 2, 'B', '2021-12-05' union all
      select 3, 'B', '2021-12-09' 
    ), battles as (
      select 'A' id, '2021-12-01' battle_date union all
      select 'A', '2021-12-03' union all
      select 'A', '2021-12-06' union all
      select 'A', '2021-12-07' union all
      select 'B', '2021-12-01' union all
      select 'B', '2021-12-02' union all
      select 'B', '2021-12-03' 
    )
    

    输出是

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 2020-06-06
      • 2014-11-26
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      相关资源
      最近更新 更多