5

我的桌子

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

在此处输入图像描述

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

  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

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

所以我的最终输出看起来

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

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

4

3 回答 3

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 |
于 2013-08-14T08:39:25.890 回答
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
于 2013-08-14T08:01:06.740 回答
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
于 2013-08-14T07:39:03.740 回答