Home  >  Q&A  >  body text

Use a SQL query to retrieve the unique identifier for a specific subject and a specified score.

<p>Want to write a SQL query to get the unique IDs of those with a math score of 80, an English score of 70, and a total score of 400 or greater. The answer will be id-1 and 2</p> <pre class="brush:php;toolbar:false;">ID Subject Marks 1 Maths 80 1 English 70 1 Hindi 80 1 Science 80 1 SST 90 2 Maths 80 2 English 70 2 Hindi 90 2 Science 80 2 SST 100 3 Maths 80 3 English 60 3 Hindi 90 3 Science 100 3 SST 100</pre> <p>I'm confused on how to insert two topics together as a filter. <br /><br />Valid query -</p><p><br /></p> <pre class="brush:php;toolbar:false;">SELECT `ID` FROM `ff` WHERE (`SUBJECT`='MATHS' AND `MARKS`= 80 AND `ID` IN (SELECT `ID` FROM `ff` GROUP BY `ID` HAVING SUM(`MARKS`) >=400) ) OR (` SUBJECT`= 'ENGLISH' AND `MARKS`=70 AND `ID` IN (SELECT `ID` FROM `ff` GROUP BY `ID` HAVING SUM(`MARKS`) >=400) )</pre> <p>But this does not give the expected results. </p>
P粉779565855P粉779565855444 days ago522

reply all(1)I'll reply

  • P粉081360775

    P粉0813607752023-08-03 09:30:06

    You can use conditional aggregation.

    SELECT `ID` 
    FROM `ff`
    GROUP BY `ID` 
    HAVING SUM(`MARKS`) >= 400  
      AND SUM(case when `SUBJECT` = 'English' then `MARKS`end) = 70 
      AND SUM(case when `SUBJECT` = 'Math' then `MARKS` end) = 80

    reply
    0
  • Cancelreply