简体   繁体   English

如何使SUMMED mySQL值最接近现有值?

[英]How to get closest SUMMED mySQL value to an existing value?

Two tables in MySQL database... MySQL数据库中的两个表...

  • players (playerid, teamid, position, firstname, lastname) 玩家(playerid,teamid,位置,名字,姓氏)
  • stats (statsid, playerid, points, year) 统计信息(statsid,playerid,积分,年份)

Let's say my baseline player has 83 points (ie the "existing value"). 假设我的基准玩家获得了83分(即“现有价值”)。

I want to find the ONE player from the database that has the closest point total to 83. 我想从数据库中找到最接近总积分83的ONE播放器。

NOTE: This existing question is similar but doesn't involve SUMMING: Select closest numerical value with MySQL query 注意:此现有问题类似,但不涉及求和: 使用MySQL查询选择最接近的数值

So this general method would work... 所以这种通用方法会起作用...

select   points,
         abs(points - 83) as distance_from_test
from     stats
order by distance_from_test
limit 1

But my issue is that there are multiple "points" entries for each player in a same year. 但是我的问题是,同一年每个球员都有多个“积分”条目。 So I want to SUM all point totals for each player first and THEN find the closest total to 83. This doesn't work, but this is basically what I want to do... 所以我想首先求和每个球员的所有总分,然后找到最接近的总分83。这是行不通的,但这基本上是我想要做的...

select   SUM(points) as totalpoints,
         abs(totalpoints - 83) as distance_from_test
from     stats
order by distance_from_test
limit 1

When I try that I get "Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)" so I'm assuming maybe you can't do this type of summing along with the abs math function. 当我尝试获取“解析错误:语法错误,意外错误”(T_ENCAPSED_AND_WHITESPACE),期望标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING)时,我假设您可能无法执行此类操作与Abs数学函数一起求和。 Can anyone confirm/deny that and point me in a smarter direction? 谁能确认/否认这一点,并指出我的明智方向?

Thanks! 谢谢!

You need to GROUP BY player and you must use the calculation instead of the alias: 您需要使用GROUP BY player并且必须使用计算方式而不是别名:

select   player,
         SUM(points) as totalpoints,
         abs(SUM(points) - 83) as distance_from_test
from     stats
GROUP BY player
order by distance_from_test
limit 1

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

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