0

I'm new to SQL and struggling with this query, any help much appreciated.

My table looks like this:

id score level
2 250 1
2 350 1
2 850 2
2 260 2
2 750 3
2 560 3

I'd like to calculate a total score as the max score from each level.

So in layman's: Total Score = Max score from level 1 + Max score from level 2 + Max score from level 3

How do I replicate that in SQL?

5
  • 3
    What have you tried so far? Commented Dec 29, 2021 at 16:56
  • 1
    please tag with database platform Commented Dec 29, 2021 at 16:58
  • 1
    GROUP BY, then SUM its result. Commented Dec 29, 2021 at 16:58
  • I think you use sub-queries like SELECT *, (SELECT SUM(table.score) WHERE level = N) AS 'level_1_score'..... Commented Dec 29, 2021 at 16:58
  • Try writing something yourself and then if it doesn't work, show us specifically what you did so we can help you along. You start it, and then we help. We don't write it for you. Show us the actual code that you've tried, and then describe what happened and what's not right, and then we can help you from there. Chances are you'll get pretty close to the answer if you just try it yourself first. Commented Dec 29, 2021 at 17:21

3 Answers 3

4

You could use SUM on the result of a sub-query:

SELECT
   SUM(max_score) AS total_score 
FROM
   (
      SELECT
         MAX(score) AS max_score 
      FROM
         YOUR_TABLE_NAME 
      GROUP BY
         level
   )
   AS max_scores
Sign up to request clarification or add additional context in comments.

2 Comments

This works great, thanks Sash, really appreciate your help. Now I'll try to group by user_id too :)
No problem, happy to help.
1
select distinct sum(max(score)) over () as "Total Score" from T group by level;

You can do the two aggregates together with group by and then a windowed sum. Distinct takes care of removing what would be the same sum repeated for every group. (In general I would encourage you to avoid too much reliance on select distinct.)

The other approaches using either CTEs/derived tables are perfectly fine. A beginner's solution would probably look more like this:

select t.level, sum(maxScore) as "Total Score"
from T t inner join
    (select level, max(score) as maxScore from T group by level) as m
        on m.level = t.level
group by t.level;

Depending on the platform you might get this to work

select level,
    sum((select max(score) from t t2 where t2.level = t.level)) as "Total Score"
from T t
group by level

Comments

0

Hi I think you are searching for this solution. I hope it will fix your question.

WITH A as (
Select MAX(score) as "MAX order" FROM "YOUR TABLE" GROUP BY level)
SELECT SUM("MAX score per level") FROM a

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.