找到点和分组的总和

时间:2013-08-14 07:30:32

标签: php mysql

我的桌子

参考:http://www.sqlfiddle.com/#!2/6be93/1

enter image description here

在这里,我想找到一所学校的总分。我正在使用以下代码。

  SELECT School, SUM(GroupPoint) AS TotalC1, SUM(C2Points) AS TotalC2,
  SUM(C3Points) AS TotalC3, SUM(GroupPoint + C2Points + C3Points) AS TotalAll 
  FROM students GROUP BY School ORDER BY TotalAll DESC LIMIT 6

参考:http://www.sqlfiddle.com/#!2/25ed3/2

我的问题,身份证1,2,3是团体比赛的获胜者。所以他们分别得到5分。但是对于那场比赛,学校只会获得5分而不是15分。一组可以由同一个ChessNO识别。

所以我的最终输出看起来

 SCHOOL   TOTALC1   TOTALC2  TOTALC3 TOTALALL
 School2   13       49       3       65       
 School1   5        4        25      34

如果有人能帮助我,我将不胜感激,

3 个答案:

答案 0 :(得分:2)

当然,你可以做一些优化。但它有效!

SELECT two.TOTALC1, one.TotalC2, one.TotalC3, one.TotalOne + two.TOTALC1 as TotalAll from 
( select School,
  SUM(C2Points) AS TotalC2,
  SUM(C3Points) AS TotalC3,
  SUM(C2Points + C3Points) AS TotalOne
FROM students GROUP BY School
ORDER BY TotalOne DESC) one
left join (select school, sum(ma) as TOTALC1 from (select school, chess, max(grouppoint) as ma from students group by school, chess) as b group by school) two
on one.school = two.school

答案 1 :(得分:2)

试试这个

SELECT 
  School,
  sum(GroupPoint),
  sum(TotalC2),
  sum(TotalC3),
  sum(GroupPoint) + sum(TotalC2) + sum(TotalC3) as total
FROM (
  SELECT
    School,
    MAX(  GroupPoint) AS GroupPoint,
    SUM(  C2Points) AS TotalC2,
    SUM(  C3Points) AS TotalC3
  FROM 
    students 
  GROUP BY 
    School,
    Chess
) subquery
GROUP BY 
  School

输出

|  SCHOOL | SUM(GROUPPOINT) | SUM(TOTALC2) | SUM(TOTALC3) | TOTAL |
-------------------------------------------------------------------
| School1 |               5 |            4 |           25 |    34 |
| School2 |              13 |           49 |            3 |    65 |

答案 2 :(得分:0)

   SELECT School, SUM(GroupPoint) AS TotalC1, SUM(C2Points) AS TotalC2,
   SUM(C3Points) AS TotalC3, SUM(GroupPoint + C2Points + C3Points) AS TotalAll 
   FROM students GROUP BY Chess ORDER BY TotalAll DESC LIMIT 6