Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find sum of points and grouping

Tags:

php

mysql

my table

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

enter image description here

Here I would like to find Total point of a School. I am using following code.

  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

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

my problem, the ID 1,2,3 are the winners of a group competition. So they get 5 points individually. But for that competition, the SCHOOL will get only 5 points not 15. A group can be Identify by same ChessNO.

So my final output looks

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

It would be grateful if anybody could help me,

like image 439
user2594154 Avatar asked Oct 03 '22 06:10

user2594154


1 Answers

Ofcourse, you can do some optimization. But it works!

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
like image 136
Bere Avatar answered Oct 10 '22 03:10

Bere