0

I need to query the same column for different values depending on another relational value.

Table is set up like this : athleteID, meetName, eventName, score

Events are all the same but there are Different Meets and my query needs to return: aid, event, score from meetName = 'whatever1', score from meetname = 'whatever2'

Ive tried every basic way about completeing this but cannot do it. I've lastly tried

SELECT distinct athleteID, event,
(select score from performances where meetName='Snowflake') as SnowScore,
(select score from performances where meetName='Valentine') as ValScore,
from performances
where event='high jump'

which returns: single-row subquery returns more than one row

My expected result would be like this:

aid, event, SnowScore, ValScore
1 , high jump, 6,  8
2 , high jump, 3,  5
3, high jump, 8, 10
Michael Ramos
  • 5,523
  • 8
  • 36
  • 51

3 Answers3

1

Does not stipulate RDMS, my answer is with SQL Server:

If you wanted to use a subquery you need to reference the atherleteID and eventName, also if there were more than one result (not clear from your question but I assume atheletes compete at multiple meets) you would need to aggregate.

There may be a better way but as a simple one off query I would probably do it like:

SELECT athleteID, eventName,
sum(CASE WHEN meetName='Snowflake' THEN score ELSE 0 END) as SnowScore,
sum(CASE WHEN meetName='Valentine' THEN score ELSE 0 END) as ValScore
FROM performances
GROUP BY atheleteID,eventName

A better longer term solution would be with PIVOT and if the meetNames will change over time you can create dynamic pivot queries, a good example I found is here

Community
  • 1
  • 1
Simon1979
  • 2,110
  • 1
  • 12
  • 15
0

Didn't try it but it gives the idea... :

SELECT athleteID, event,
sum(case when meetName='Snowflake' then score else 0 end) as SnowScore,
sum(case when meetName='Valentine' then score else 0 end) as ValScore,
from performances
group by athleteID, event
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30
0

I would like to add that Natural Inner Join is what should've been done here for basic(non-commercial) sql.

Syntax would've been: select * from (subquery1) NIJ (subquery2)

The subqueries syntax:

select athleteID, score as ValScore from performances, NIJ athletes where meet =‘Valentin’ and event=‘beam’

and

select athleteID, score as SnowScore from performances, NIJ athletes where meet =‘SnowFlake’ and event=‘beam’
Michael Ramos
  • 5,523
  • 8
  • 36
  • 51