4

I am wanting to calculate the difference between the max(value) returned from a database against a row value returned.

Example Data

  1. 400
  2. 300
  3. 200
  4. 100

max(value return) = 400

Returned result should be:

  1. 0 (no difference between the max value and row value)
  2. 100
  3. 200
  4. 300

etc

Any ideas how this could achieve?

This is current mySQL statement I am using:

SELECT userName, totalPoints , (totalPoints) AS gap
FROM userTable
WHERE value='1'  
ORDER BY totalPoints DESC

s

2
  • I would think that (MAX(totalPoints) - totalPoints) as gap would work. Did you try that? Aug 15, 2014 at 15:50
  • It is not clear if the max value should be for the entire table or only for rows where value = '1'
    – Adrian
    Aug 15, 2014 at 16:04

5 Answers 5

4

Try this below soln.

SELECT A.MaxtotalPoints - A.totalPoints AS GAP
FROM
(
SELECT userName, totalPoints , MAX(totalPoints) MaxtotalPoints
FROM userTable
WHERE value='1'  
) A
ORDER BY GAP;
1

I'm not actually advising that you use this solution, but you could do this with a 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;

Usually I prefer standard SQL solutions (i.e. using the calculated max() value), but I realized that this would also work.

1

Try this:

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
2
  • You should add in the where clause in the appropriate places to really answer the question. Aug 15, 2014 at 15:54
  • Hmm I would have expected it to work but MySql seems to do an implicit limit - you only get one row (with the first username and the max points) in the sub-select. See my answer for a working variant. i first thought the join condition was just uneccessary, but it actually causes a problem trying to make a sub-select which can support a join condition
    – Adam
    Aug 15, 2014 at 16:33
0
SELECT x.*,MAX(y.data)-x.data FROM my_table x,my_table y GROUP BY x.id;
0

Assuming you want the diff between that users points and the from the max-for-all-users, but only want data for the one user then this works:

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

Can also be run without the where condition if you want the gap for all users.

If that's not what you want then you need to explain better what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.