简体   繁体   English

如何计算SQL中另一个事件后立即发生的事件?

[英]How Can I Count occurrences that immediately follow another event in SQL?

I have taken a data set and run the following query to filter it to the events that I want: 我已获取一个数据集并运行以下查询以将其过滤到所需的事件:

SELECT player_id, team_id, pbp_id, event_desc_id 
FROM GamsetPBP 
WHERE event_desc_id = '2FGM' OR event_desc_id = '3FGM' OR event_desc_id = '2FGA' OR event_desc_id ='3FGA' OR event_desc_id = 'O';

When I do this, it shows all the instances of those events. 当我这样做时,它将显示这些事件的所有实例。 I want to count all instances where a 2FGM, 3FGM, 2FGA, or 3FGA occurs within two events of an 'O' event based on the pbp_id. 我想计算基于pbp_id在'O'事件的两个事件中发生2FGM,3FGM,2FGA或3FGA的所有实例。

So if an 'O' has a pbp_id of 45 and there is a '2FGM' with a pbp_id of 47, I want to be able to count it. 因此,如果“ O”的pbp_id为45,而有一个“ 2FGM”的pbp_id为47,我希望能够对其进行计数。 Any suggestions on how I can Count occurrences within a range like this? 关于如何计算这样范围内的事件的任何建议?

From what I understand you could use this query: 据我了解,您可以使用以下查询:

SELECT     COUNT(DISTINCT a.pbp_id)
FROM       GamsetPBP a
INNER JOIN GamsetPBP b
        ON b.pbp_id BETWEEN a.php_id + 1 AND a.php_id + 2
       AND b.event_desc_id IN ('2FGM', '3FGM', '2FGA', '3FGA')
       -- ... any other join conditions on player_id? team_id?
WHERE      a.event_desc_id = 'O';

This counts the number of "O" events that have an event following it with an ID that is one or two greater, and which have a type that is '2FGM', '3FGM', '2FGA', or '3FGA'. 这将计算紧随其后的事件的ID大于或等于1或2,并且类型为“ 2FGM”,“ 3FGM”,“ 2FGA”或“ 3FGA”的“ O”事件的数量。 There could of course be two of those following, but then the above query will only count that as one instance. 当然可以有以下两个,但是上面的查询仅将其视为一个实例。

If you want to count such "doubles" separately, then remove the word DISTINCT . 如果要分别计算此类“双打”,则删除单词DISTINCT

From your comment it became clear that the two records (the one with "O" and the one with the other type) should belong to the same team and be counted per team, with the highest counts listed first. 从您的评论中可以很清楚地看到,两个记录(一个带有“ O”,另一个带有另一种类型)应该属于同一支球队,并且按球队计算,最高的得分在前。

In that case add the team condition in the join , select the team ID, group by it and order by the count: 在这种情况下,在join添加团队条件,选择团队ID,对其进行分组,然后按计数排序:

SELECT     a.team_id,
           COUNT(DISTINCT a.pbp_id)
FROM       GamsetPBP a
INNER JOIN GamsetPBP b
        ON b.pbp_id BETWEEN a.php_id + 1 AND a.php_id + 2
       AND b.event_desc_id IN ('2FGM', '3FGM', '2FGA', '3FGA')
       AND b.team_id = a.team_id
WHERE      a.event_desc_id = 'O'
GROUP BY   a.team_id
ORDER BY   2 DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM