搜尋

首頁  >  問答  >  主體

使用SQL查詢擷取特定科目和指定分數的唯一識別碼。

<p>想要寫一個SQL查詢,以獲得數學成績為80分、英文成績為70分,總分大於等於400分的唯一ID。答案將是id-1和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>我很困惑如何將兩個主題一起插入作為過濾器。 <br /><br />有效的查詢 -</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>但這並沒有給出預期的結果。 </p>
P粉779565855P粉779565855542 天前570

全部回覆(1)我來回復

  • P粉081360775

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

    您可以使用條件聚合。

    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

    回覆
    0
  • 取消回覆