SUM() based on a different condition to the SELECT

后端 未结 3 1735
生来不讨喜
生来不讨喜 2021-02-05 20:56

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

相关标签:
3条回答
  • 2021-02-05 21:18

    Do the sum as a subselect, making sure that you select an additional column (don't forget to group by that column) and join the result of this subselect to the main query using the common field.

    Template:

    Select col1, 
    col2 as t,x.thesum
    From table t left join 
    ( select sum(colx) as thesum, col1 from t where ...
     Group by col1) x on t.col1=x.col1
     Where ....
    
    0 讨论(0)
  • 2021-02-05 21:31

    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  
    
    0 讨论(0)
  • 2021-02-05 21:38
    SELECT ... 
    SUM(CASE
    WHEN track_id <= [your_value] THEN total_points
    ELSE 0
    END
    ) AS total_points, .... 
    
    0 讨论(0)
提交回复
热议问题