我想计算从数据库返回的max(值)与返回的行值之间的差异。
示例数据
max(值返回)= 400
返回的结果应为:
等
任何想法如何实现?
这是我正在使用的当前mySQL语句:
SELECT userName, totalPoints , (totalPoints) AS gap
FROM userTable
WHERE value='1'
ORDER BY totalPoints DESC
取值
答案 0 :(得分:1)
试试这个:
SELECT a.*, b.maxTotalPoints - a.totalPoints as gap
from userTable a
INNER JOIN
( SELECT userName, max(totalPoints) as maxTotalPoints
FROM userTable
) b on (a.userName = b.userName)
WHERE a.value='1'
ORDER BY a.totalPoints DESC
答案 1 :(得分:1)
我实际上并没有建议您使用此解决方案,但您可以使用MySQL hack执行此操作:
SELECT userName, totalPoints,
( totalpoints - if(@totalpoints = -1, (@totalpoints := totalpoints), totalpoints) ) AS gap
FROM userTable ut cross join
(select @totalpoints := -1) vars
WHERE value = '1'
ORDER BY totalPoints DESC;
通常我更喜欢标准的SQL解决方案(即使用计算出的max()
值),但我意识到这也可以。
答案 2 :(得分:0)
请尝试以下解决方案。
SELECT A.MaxtotalPoints - A.totalPoints AS GAP
FROM
(
SELECT userName, totalPoints , MAX(totalPoints) MaxtotalPoints
FROM userTable
WHERE value='1'
) A
ORDER BY GAP;
答案 3 :(得分:0)
SELECT x.*,MAX(y.data)-x.data FROM my_table x,my_table y GROUP BY x.id;
答案 4 :(得分:0)
假设你想要那些用户点之间的差异和来自max-for-all-users的差异,但只想要一个用户的数据,那么这是有效的:
select u.username, u.totalpoints, m.m - u.totalpoints as gap
from usertable u
join ( select max(totalpoints) as m from usertable) m
where u.username = 4
如果你想要所有用户的差距,也可以在没有where条件的情况下运行。
如果那不是你想要的,那么你需要更好地解释你想要的东西。