SUM()基于SELECT的不同条件

时间:2011-10-04 23:36:54

标签: mysql sql

嗨有没有办法可以根据与SELECT语句的其余部分不同的条件来执行SUM(total_points),所以我希望每行的SUM(total_points)是< =到$ choosentrack?但SELECT语句的其余条件是它们的下面。我需要他们全部归还。我正在填写一张联赛桌。

非常感谢您的帮助。

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

3 个答案:

答案 0 :(得分:25)

您还可以将总和放在case语句中,其中case判断另一个条件,然后只对那些条件为真的记录求和...

  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  

答案 1 :(得分:3)

SELECT ... 
SUM(CASE
WHEN track_id <= [your_value] THEN total_points
ELSE 0
END
) AS total_points, .... 

答案 2 :(得分:1)

将和作为子选择,确保选择其他列(不要忘记按该列分组)并使用公共字段将此子选择的结果连接到主查询。

模板:

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 ....