0

世界!

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

等级 ID 级别日期
1 一个 2021-12-02
2 一个 2021-12-04
3 一个 2021-12-08
1 2021-12-02
2 2021-12-05
3 2021-12-09

和第二个“战斗”表:

ID 战斗日期
一个 2021-12-01
一个 2021-12-03
一个 2021-12-06
一个 2021-12-07
2021-12-01
2021-12-02
2021-12-03

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

当battle_date > level_X-1_date,但battle_date < level_X_date,表示本次战斗需要达到X级,应计入X级。

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

结果表应如下所示:

等级 avg_battle_count
1 1
2 1.5
3 1

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

4

2 回答 2

1

考虑以下方法(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' 
)

输出是

在此处输入图像描述

于 2021-12-09T21:32:25.747 回答
0

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

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
于 2021-12-09T20:34:10.953 回答