简体   繁体   English

MySQL对符合特定条件的行的max(date)之前的所有计数

[英]MySql count all before max(date) of row that meets certain criteria

I'm trying to get the last recorded loss, then count the number of wins after that to calculate a win streak. 我正在尝试获取最后记录的亏损,然后计算此后的获胜次数以计算连胜纪录。

BEGIN
SET @maxDate:=(SELECT MAX(date) from game_scores where     
user_score<opponent_score and user_id=1);

SELECT @maxDate as last_loss, COUNT(*) as streak from game_scores
WHERE  user_score>opponent_score and date>@maxDate and user_id=1;

END

But I keep getting syntax errors at the SET @maxDate line. 但是我在SET @maxDate行中不断收到语法错误。 Am I close? 我靠近吗?

You can do this in a single shot if you join to the query for the last loss date. 如果您加入最后一个损失日期的查询,则可以一次完成此操作。

Also note that, if you've already located the user's last loss date, any of their records after that will be wins so your second query doesn't need to check the user score against the opponent score. 另请注意,如果您已经找到了用户的上次丢失日期,则此后的任何记录都将获胜,因此您的第二次查询无需对照对手得分来检查用户得分。

SELECT
  last_recorded_loss.maxDate AS last_loss,
  COUNT(*) AS streak
FROM game_scores
INNER JOIN (
  SELECT MAX(date) AS maxDate
  FROM game_scores
  WHERE user_score < opponent_score
    AND user_id = 1
  ) last_recorded_loss
  ON game_scores.date > last_recorded_loss.maxDate AND
     game_scores.user_id = 1

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

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