如何将用户变量用作包含GROUP BY语句的内部联接查询的计数器?

时间:2015-02-23 13:13:20

标签: mysql aggregate-functions

我有2个表oddsmatches

匹配:有match_idmatch_date

赔率:有idtimestampresultodd_valueuser_idmatch_id

我有一个查询,从每个用户的表中获取以下信息:

  1. 奖金:每位用户的获胜赌注。 (当odds.result = 1时)
  2. 输了:每个用户丢失的赌注。(当odds.result!= 1时)
  3. points:每个用户的点数(odds.odd_value的总和)。
  4. 奖励:对于每个连续5次奖金,我想为此变量添加额外奖励。 (对于每个用户)
  5. 如何计算奖金? 我尝试使用此查询并遇到问题:(您可以在此处查看SQL Fiddle

    计算的奖金不适合所有用户:

    第一位用户:(奖金:13,奖金= 2)。

    第二位用户:(奖金:8,奖金= 2)这里奖金应为1。

    第三位用户:(奖金:14,奖金= 3)这里奖金应为2。

    为什么查询无法正确计算bonus

            select  d.user_id,
            sum(case when d.result = 1 then 1 else 0 end) as winnings, 
            sum(case when d.result = 2 then 1 else 0 end) as loses,
            sum(case when d.result = 1 then d.odd_value else 0 end) as points,
            f.bonus
    FROM odds d
        INNER JOIN
        (
          SELECT  
                user_id,SUM(CASE WHEN F1=5 THEN 1 ELSE 0 END) AS bonus
            FROM
            (
              SELECT 
                user_id,
                CASE WHEN result=1 and @counter<5 THEN @counter:=@counter+1 WHEN result=1 and @counter=5 THEN @counter:=1 ELSE @counter:=0 END AS F1
              FROM odds o
              cross join (SELECT @counter:=0) AS t
              INNER JOIN matches mc on mc.match_id = o.match_id
               WHERE MONTH(STR_TO_DATE(mc.match_date, '%Y-%m-%d')) = 2 AND 
                      YEAR(STR_TO_DATE(mc.match_date, '%Y-%m-%d')) =  2015 AND
                      (YEAR(o.timestamp)=2015 AND MONTH(o.timestamp) = 02)            
            ) Temp
            group by user_id
            )as f on f.user_id = d.user_id
          group by d.user_id
    

1 个答案:

答案 0 :(得分:0)

我不确定您的结果与matches表,

有何关联

如果需要,您可以添加WHERE / INNER JOIN子句。

这是link to fiddle

根据您的意见

last iteration

这是一个查询:

SET @user:=0;

select  d.user_id,
        sum(case when d.result = 1 then 1 else 0 end) as winnings, 
        sum(case when d.result = 2 then 1 else 0 end) as loses,
        sum(case when d.result = 1 then d.odd_value else 0 end) as points,
        f.bonus
FROM odds d
    INNER JOIN
    (
      SELECT  
            user_id,SUM(bonus) AS bonus
        FROM
        (
          SELECT 
            user_id,
            CASE WHEN result=1 and @counter<5 AND @user=user_id THEN @counter:=@counter+1 

                 WHEN result=1 and @counter=5 AND @user=user_id THEN @counter:=1 

                 WHEN result=1 and @user<>user_id THEN @counter:=1 
                 ELSE 
                 @counter:=0 
            END AS F1,
            @user:=user_id,
            CASE WHEN @counter=5 THEN 1 ELSE 0 END AS bonus 
          FROM odds o
          ORDER BY user_id , match_id         
        ) Temp
        group by user_id
        )as f on f.user_id = d.user_id
      group by d.user_id