我有2个表odds
和matches
:
匹配:有match_id
和match_date
赔率:有id
,timestamp
,result
,odd_value
,user_id
,match_id
我有一个查询,从每个用户的表中获取以下信息:
如何计算奖金? 我尝试使用此查询并遇到问题:(您可以在此处查看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
答案 0 :(得分:0)
我不确定您的结果与matches
表,
如果需要,您可以添加WHERE
/ INNER JOIN
子句。
这是一个查询:
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