Mysql 如何检查同一查询中聚合函数的值?

Mysql 如何检查同一查询中聚合函数的值?,mysql,aggregate-functions,Mysql,Aggregate Functions,这个MySQL查询在“字段列表”中给了我这个错误'Unknown column'winnings' SELECT o.user_id, sum(case when o.result = 1 or o.result=2 or o.result = 0 then 1 else 0 end) as tahmins_no, sum(case when o.result = 1 then 1 else 0 end) as winnings, sum(case when o.result = 2

这个MySQL查询在“字段列表”中给了我这个错误
'Unknown column'winnings'

SELECT  
o.user_id, 
sum(case when o.result = 1 or o.result=2 or o.result = 0 then 1 else 0 end) as tahmins_no, 
sum(case when o.result = 1 then 1 else 0 end) as winnings, 
sum(case when o.result = 2 then 1 else 0 end) as loses,
sum(case when winnings = 10 then 0.5 else 0 end) as counter 
FROM `odds_tahminler` o
我知道
winnings
sum()
聚合函数的值,但是有没有办法在查询中检查
winnings
值?

您可以尝试:

SELECT 
o.user_id, 
sum(case when o.result = 1 or o.result=2 or o.result = 0 then 1 else 0 end) as tahmins_no, 
sum(case when o.result = 1 then 1 else 0 end) as winnings, 
sum(case when o.result = 2 then 1 else 0 end) as loses,
sum(case when winnings = 10 then 0.5 else 0 end) as counter 
FROM `odds_tahminler` o
GROUP BY o.user_id
HAVING counter>2

不能在select中使用聚合列。但是,在计算所有聚合列之后,可以使用子查询来获取计数器值

计数器值是如何计算的?我假设计数器应该是(winnings-10)/2,如果至少有10个winnings,否则为0。在这种情况下,您可以通过此查询获得它

SELECT O.*,
       GREATEST( (O.winnings - 10) / 2, 0) as counter            
  FROM
       (
          SELECT u.username, 
                 o.user_id, 
                 sum(case when o.result = 1 or o.result=2 or o.result = 0 then 1 else 0 end) as tahmins_no, 
                 sum(case when o.result = 1 then 1 else 0 end) as winnings, 
                 sum(case when o.result = 2 then 1 else 0 end) as loses
            FROM `odds_tahminler` o
       ) as O

我只看到了
o
表,你的
u
表在哪里?Alex你说得对,我编辑了它
检查*winnings*值是什么意思?查询结果会显示什么?不是吗?我想你在这个答案中遗漏了一些东西,我希望
计数器
为每10个
奖金增加1个。可能吗?我的意思是,我们应该每10次连续赢款向计数器递增一次,然后使赢款值为零,如果我们在达到10次连续赢款之前面临亏损,我们也应该使赢款为零,所以你要计算有多少次连续赢款。遗憾的是,您不能使用聚合函数来实现这一点。这一定是一种方法,但我需要时间来考虑,如果我找到解决方案,我会再次回答。