在一个部分中找到两个学生的最高分

时间:2013-08-11 01:59:36

标签: php mysql

我的桌子

enter image description here

我想在这里显示

每个部分获得最高分的2名学生的姓名(C1分数与C3分数之和)。同时展示他们的每个比赛和积分。还需要显示重复的标记。

请仅查询一个部分。

所以最终输出看起来

enter image description here

2 个答案:

答案 0 :(得分:3)

这将为您提供单个部分的结果:

SELECT
  Name,
  SUM(C1Points) AS TotalC1,
  SUM(C2Points) AS TotalC2,
  SUM(C3Points) AS TotalC3,
  SUM(C1Points + C2Points + C3Points) AS TotalAll
FROM myTable
WHERE Section = 'Section1'
GROUP BY Name
ORDER BY TotalAll DESC
LIMIT 2

使用MySQL一次阅读所有部分很复杂。最好是阅读所有内容并正确排序,然后使用PHP获取每个部分的前两行:

SELECT
  Name,
  Section,
  SUM(C1Points) AS TotalC1,
  SUM(C2Points) AS TotalC2,
  SUM(C3Points) AS TotalC3,
  SUM(C1Points + C2Points + C3Points) AS TotalAll
FROM myTable
GROUP BY Name, Section
ORDER BY Section, TotalAll DESC

你会得到这样的结果集:

Section 1 first place name and scores
Section 1 second place name and scores
Section 1 third place name and scores
. . .
Section 1 last place name and scores
Section 2 first place name and scores
Section 2 second place name and scores
and so on...

按照这样的顺序排列,抓住每个部分的前两行将是PHP中的孩子游戏。

答案 1 :(得分:2)

此解决方案将同时为您提供所有部分的输出,您只需要修改表格的结构并添加总计

想象你有这个

CREATE TABLE STUDENT (NAME VARCHAR(10), SECTION VARCHAR(20), 
                  C1 INTEGER, C2 INTEGER, C3 INTEGER);

INSERT INTO STUDENT VALUES ('S1','Section1',5,0,3),
                ('S2','Section2',0,0,5),
                ('S3','Section3',5,5,5),
                ('S4','Section3',3,3,0),
                ('S5','Section1',5,0,3),
                ('S6','Section2',0,1,0),
                ('S7','Section3',0,0,0),
                ('S8','Section3',5,0,5),
                ('S9','Section1',5,0,3),
                ('S10','Section2',0,3,0),
                ('S11','Section1',3,0,0),
                ('S12','Section3',5,5,5),
                ('S13','Section1',0,1,1),
                ('S14','Section2',3,5,0),
                ('S15','Section3',1,0,0);

现在你需要添加

ALTER TABLE STUDENT ADD COLUMN TOTAL INTEGER;

并更新值

UPDATE STUDENT SET TOTAL = C1+C2+C3;

然后您可以运行此查询

   SELECT SECTION,
       NAME,
       C1,
       C2,
       C3,
       TOTAL
FROM STUDENT
WHERE CONCAT(SECTION,TOTAL) IN
    (SELECT IDENTIFIER
     FROM
       (SELECT CONCAT(SECTION,MAX(TOTAL)) AS IDENTIFIER,
               SECTION,
               MAX(TOTAL) AS MARKS
        FROM STUDENT
        GROUP BY SECTION
        UNION SELECT CONCAT(SECTION,MAX(TOTAL)) AS IDENTIFIER,
                     SECTION,
                     MAX(TOTAL) AS MAKRS
        FROM STUDENT AS A
        WHERE TOTAL <
            (SELECT MAX(TOTAL)
             FROM STUDENT
             WHERE SECTION = A.SECTION)
        GROUP BY SECTION) AS RESULT)
ORDER BY SECTION,
         TOTAL DESC

您可以看到结果

enter image description here

http://www.sqlfiddle.com/#!2/f18e1/24/0

希望这有帮助,根本不需要PHP,尽管在PHP或其他服务器端脚本中执行此操作实际上可能更有效