Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUM() based on a different condition to the SELECT

Tags:

sql

mysql

Hi is there a way that I can do the SUM(total_points) based on a different condition to the rest of the SELECT statement, so I want the SUM(total_points) for every row which is <= to $chosentrack? but the rest of the conditions of the SELECT statement to be what they are below. I need them to all be returned together..as I am populating a league table.

Thanks a lot for any help.

SELECT
    members.member_id,
    members.teamname,
    SUM(total_points) as total_points,
    total_points as last_race_points 
FROM
    members,
    members_leagues,
    member_results 
WHERE
    members.member_id = members_leagues.member_id 
    AND members_leagues.league_id = '$chosenleague' 
    AND member_results.track_id = '$chosentrack' 
    AND members_leagues.start_race = '$chosentrack' 
    AND member_results.member_id = members_leagues.member_id
GROUP BY
    members.member_id 
ORDER BY
    member_results.total_points DESC,
    last_race_points DESC, 
    members.teamname DESC
like image 618
user970117 Avatar asked Oct 04 '11 23:10

user970117


1 Answers

You can also put the sum inside a case statement, where the case evaluates the other condition, and then only sum thoses records where the condition is true...

  SELECT m.member_id, m.teamname, 
    Sum(Case When r.track_Id = '$chosentrack' 
         Then total_points Else 0 End) TotalChosenTrackPoints,
    Sum(Case When r.track_Id < '$chosentrack' 
         Then total_points Else 0 End) TotalLessThanChosenTrackPoints, 
    total_points as last_race_points  
 FROM members m
    Join members_leagues l
       On l.member_id = m.member_id  
    Join member_results r
       On r.member_id = m.member_id
 Where l.league_id = '$chosenleague'
    And l.start_race = '$chosentrack'
 Group By m.member_id
 Order By r.total_points Desc, 
     last_race_points  Desc, m.TeamName Desc  
like image 163
Charles Bretana Avatar answered Oct 01 '22 07:10

Charles Bretana