1

Why this query instead of displaying the sum of points for each user, it display the sum of all together

I have written an SQL query that displays the sum of all point for all users, whereas I would like it to: display the sum of points for each user.

The table that I have written contains the following:

id  |  Score
1   |   20
2   |   30
2   |   50
1   |   10

Total table :

id | points

1  | 30

1  | 40

What I want is to add the score for user(1) = 30 and user(2) = 80

Id: 1 = 30 = Fail
Id: 2 = 80 = Pass

The query I have written :

$query = "SELECT SUM(sg.score) as sum, SUM(a.total) as suma FROM points as sg, totalpoints as a
          WHERE a.id = 1 GROUP BY sg.id";

And related PHP code is as follows:

<?php
  foreach($rowsum as $rowsm): 
    if( ' '. htmlentities($rowsm['sum']) . '' > 50  )
      echo 'Pass';
    else if( ' '. htmlentities($rowsm['sum']) . '' >= 40  )
      echo 'Failed';

    echo ' ' . htmlentities($rowsm['sum'], ENT_QUOTES, 'UTF-8') . '<br>';

  endforeach;
?>
0

4 Answers 4

1

You need to group by the users ID:

SELECT SUM(score) as sum FROM points GROUP BY id ORDER BY id

You also have an incorrect WHERE clause

WHERE id=id

isn't needed.

Sign up to request clarification or add additional context in comments.

Comments

1

I guess you should look forward using the GROUP BY clause :

SELECT 
   SUM(score) AS sum 
FROM 
   points 
 GROUP BY 
   id 
 ORDER BY 
   id

Comments

0

You've omitted the GROUP BY clause:

$query = "SELECT SUM(score) as `sum` FROM points GROUP BY id ORDER BY id";

Your WHERE clause wasn't needed.

2 Comments

Thank you :), and It is posible to first sum all the values and then do the sum for id
If you want the total sum included you can do it with a subselect:
0

You need to do group by as below and it will give you the sum of scores for each user

SELECT SUM(score) as sum FROM points 
group by id 
ORDER BY id

If you need to find it for a specific user just add a where condition as

SELECT SUM(score) as sum FROM points 
where id = 1

The above will give the sum of scores for id = 1 and can change for other values as needed.

4 Comments

I updated my question, hope you can help is a diff query
In this case you need to use the first query and will return exactly what you want.
My problem is that total point, Im getting it from a different table
different table ? you may need to add the table and data in that case to your question.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.