0

I have a table like this:

Section    TestID        Score

Section1   1             50
Section2   1             32
Section3   1             22
Section1   2             22
Section2   2             17 
Section3   2             42

I'm looking to produce a table with each section and it's scores against all testIDs (up to a maximum of 3 scores). Is it possible to use a group by condition to produce a table similar to this:

Section    Score1     Score2

Section1   50          22
Section2   32          17
Section3   22          42

2 Answers 2

1

With ROW_NUMBER() window function and conditional aggregation:

select t.section,
  max(case when t.rn = 1 then t.score end) score1,
  max(case when t.rn = 2 then t.score end) score2
from (
  select *, row_number() over (partition by section order by testid) rn
  from tablename
) t
group by t.section

See the demo.
Results:

> section  | score1 | score2
> :------- | -----: | -----:
> Section1 |     50 |     22
> Section2 |     32 |     17
> Section3 |     22 |     42
Sign up to request clarification or add additional context in comments.

Comments

0

You can use conditional aggregation:

select section,
       max(case when testid = 1 then score end) as score_1,
       max(case when testid = 2 then score end) as score_2
from t
group by section;

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.