簡體   English   中英

如何使用 case 獲取行總和的最大值

[英]How do I get the max value of the sum of rows using case

我有一個結果門戶,根據每個學期的單個主題輸入結果。 我需要從三個學期(1學年)的總和中獲得每門學科的最高分、平均分和最低分

我的代碼為每個學生獲取每個學期的每個科目,但在為每個科目添加三個學期后,我需要獲得最高、平均和最低分數

我的查詢

SELECT results.subjects,
    MAX(CASE WHEN results.term = 'First' THEN results.examTotal END) 'First'
    ,MAX(CASE WHEN results.term = 'Second' THEN results.examTotal END) 'Second'
    ,MAX(CASE WHEN results.term = 'Third' THEN results.examTotal END) 'Third'
FROM results 
WHERE studId = '".$RegNo."' 
GROUP BY   results.subjects
ORDER BY results.subjects ASC

我希望有一張桌子

+-----+-------+--------+-----+----------+---------+---------+-------+
+Sub  + First + Second +Third+(Total/3) + Highest + Average + Lowest+
+-----+-------+--------+-----+----------+---------+---------+-------+
+ Eng +  79   +  80    +  67 +  75.33   +   80    +  60     +  45   +
+-----+-------+--------+-----+----------+---------+---------+-------+
+Maths+   60  +  77    + 73  +   70     +   90    +  60     +  40   +
+-----+-------+--------+-----+----------+---------+---------+-------+

您可以獲得查詢所需的所有列,除了(Total/3)最好使用外部查詢來計算它:

SELECT
  t.subjects, t.First, t.Second, t.Third,
  round((t.First + t.Second + t.Third) / 3.0, 1) `(Total/3)`,
  t.Highest, t.Average, t.Lowest
FROM (
    SELECT 
      subjects,
      MAX(CASE WHEN term = 'First' THEN examTotal END) First,
      MAX(CASE WHEN term = 'Second' THEN examTotal END) Second,
      MAX(CASE WHEN term = 'Third' THEN examTotal END) Third,
      MAX(examTotal) Highest, 
      MIN(examTotal) Lowest,
      AVG(examTotal) Average
    FROM results 
    WHERE studId = '".$RegNo."' 
    GROUP BY subjects
) t
ORDER BY t.subjects ASC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM