gpt4 book ai didi

php - 如何获得最接近现有值的 SUMMED mySQL 值?

转载 作者:行者123 更新时间:2023-11-29 06:27:07 24 4
gpt4 key购买 nike

MySQL 数据库中的两个表...

  • 球员(playerid, teamid, position, firstname, lastname)
  • 统计数据(statsid、playerid、积分、年份)

假设我的基线球员有 83 分(即“现有值”)。

我想从数据库中找到总分最接近 83 的一名球员。

注意:此现有问题类似但不涉及求和:Select closest numerical value with MySQL query

所以这个通用方法会起作用...

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

但我的问题是同一年每个玩家都有多个“积分”条目。所以我想先对每个玩家的所有总分求和,然后找到最接近 83 的总分。这行不通,但这基本上就是我想做的......

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

当我尝试我得到“解析错误:语法错误,意外的''(T_ENCAPSED_AND_WHITESPACE),期望标识符(T_STRING)或变量(T_VARIABLE)或数字(T_NUM_STRING)”所以我假设你可能做不到这种类型的求和以及 abs 数学函数。任何人都可以证实/否认这一点并为我指明更明智的方向吗?

谢谢!

最佳答案

您需要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

关于php - 如何获得最接近现有值的 SUMMED mySQL 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com