1

I try to update my users points based on a SUM from another table.

UPDATE users u
INNER JOIN
(
    SELECT user_id, SUM(user_score_for_answer) as total
    FROM answer_histories
    GROUP BY user_id, total
) a ON users.id = a.user_id
SET U.points = a.total

ERROR: syntax error at or near "INNER"

2 Answers 2

2

In Postgres, the syntax looks like:

UPDATE users u
    SET points = a.total
FROM (SELECT user_id, SUM(user_score_for_answer) as total
      FROM answer_histories
      GROUP BY user_id
     ) a 
WHERE u.id = a.user_id;
Sign up to request clarification or add additional context in comments.

1 Comment

A good practice in SQL language is avoiding aggregate functions (such as SUM, COUNT, MAX, etc.) in the 'GROUP BY' clause, so 'total' is unnecessary in this example, i.e. 'GROUP BY user_id' is enough to achieve what you want. For more information, please have a look at: w3schools.com/sql/sql_groupby.asp
0

Gordon's answer is great, just getting small error - "aggregate functions are not allowed in GROUP BY" which can be fixed by simply removing total from GROUP BY.

*(I could not put this in comment due to insufficient reputation).

Comments

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.