计算值在连续28天中出现的次数

时间:2019-09-12 12:17:10

标签: sql db2

我是这个社区的新手,我想需要您的帮助。 我有一个查询,显示所有在2019年连续28天至少达到5个进球的球员。现在我还需要知道如果他们至少做出5个进球,他们实际创造了多少个进球。

您可以在下面看到我已经拥有的查询。

select player_id from
(
  select    a.player_id, 
          min(days(a.date)-days(b.date)) as time_period
  from
  (
    select  *
    from
    (
      select    player_id, 
              date, 
              row_number() over (partition by player_id order by date asc) as goals 
      from  matches m
      where             date>date('01.01.2019')
      and       player_id<>''
    )
    where goals >=5
  ) a
  join
  (
    select  player_id, 
            date, 
            row_number() over (partition by player_id order by date asc) as goals
    from    matches m
    where       date>date('01.01.2019')
    and player_id<>'' 
  ) b
  on        a.player_id=b.player_id
  and       a.goals=(b.goals+4)
  group by  a.player_id
) Z
where time_period<=28 

上面的查询向我提供了连续28天达到5个或更多进球的所有球员,但没有显示在此期间他们实际创造了多少个进球。

2 个答案:

答案 0 :(得分:1)

考虑以下示例:

select *
from 
(
  select 
    d, player_id
  , count(1) over (partition by player_id order by days(d) range between 28 preceding and current row) as goals
  from
  (
  values
    (date('2019-01-01'), 1)
  , (date('2019-01-28'), 1)
  , (date('2019-02-01'), 1)
  , (date('2019-02-02'), 1)
  ) t(d, player_id)
)
--where goals>=2
;

D          PLAYER_ID GOALS
---------- --------- -----
2019-01-01         1     1
2019-01-28         1     2
2019-02-01         1     2
2019-02-02         1     3

GOALS列中,相对于每个Dplayer_id列中的日期而言,前几天的目标计数不超过28。如示例中所示,自从过去28天以来,该球员承诺了所需的进球数之后,每个球员可能会有多个日期。

答案 1 :(得分:0)

尝试如下

select player_id,total_goal from
(
  select    a.player_id, sum(a.goals) as total_goal,
          min(days(a.date)-days(b.date)) as time_period
  from
  (
    select *
    from
    (
      select    player_id, 
              date, 
              row_number() over (partition by player_id order by date asc) as goals 
      from  matches m
      where             date>date('01.01.2019')
      and       player_id<>''
    )
    where goals >=5
  ) a
  join
  (
    select  player_id, 
            date, 
            row_number() over (partition by player_id order by date asc) as goals
    from    matches m
    where       date>date('01.01.2019')
    and player_id<>'' 
  ) b
  on        a.player_id=b.player_id
  and       a.goals=(b.goals+4)
  group by  a.player_id
) Z
where time_period<=28