回答

收藏

SUM()基于与SELECT不同的条件

技术问答 技术问答 257 人阅读 | 0 人回复 | 2023-09-14

嗨,有一种方法可以根据与SELECT语句其余部分不同的条件来执行SUM(total_points),所以我希望每行* p9 Q: P7 u+ {* ^' l
非常感谢您的帮助。
  P$ S( ?9 Z; F1 `1 pSELECT9 k/ w: b& p7 [( S1 K
    members.member_id,& b, Y6 X9 z# ^2 q6 e, K$ [) h
    members.teamname,& Q9 W: w! [4 j- M5 k
    SUM(total_points) as total_points,( |$ H( R' M( ^
    total_points as last_race_points
* R1 T7 B" N; O  T! nFROM
" b9 n* E  ?  \+ [, m& t! x    members,1 z" w1 v7 y6 M' C% b
    members_leagues,
7 ?: ?5 ?/ B" J2 p4 \+ v7 r' o    member_results # q$ j5 v; i2 c, s6 v8 N, [) g/ U
WHERE
; m( K* i1 S- E- K4 J2 S% N8 p    members.member_id = members_leagues.member_id % E2 }+ n, Q) b
    AND members_leagues.league_id = '$chosenleague' 2 H* q( p2 n2 [! A, b  U
    AND member_results.track_id = '$chosentrack' 8 j& D9 Z8 I' D  l' K
    AND members_leagues.start_race = '$chosentrack'
$ g, ~; `& N2 \    AND member_results.member_id = members_leagues.member_id$ d, h% @9 N+ c7 o: C
GROUP BY
: Q! e1 ?( f* {: C2 U4 F    members.member_id
3 A5 z7 Q: W; x: j( P6 L: iORDER BY
2 m0 [# L- ]% S0 R    member_results.total_points DESC,
9 [: O' u9 D# {; K; {" B* [: k4 e    last_race_points DESC, 6 S5 K# r. J* W. q' S9 B& Z' n, E
    members.teamname DESC, }; {* F) `6 }
                * P9 Y7 B9 C0 m5 ]# i
解决方案:5 T$ i9 C" ^/ U: v
                ; S9 h2 X5 h- t8 b* G. e
+ U. x2 L4 B! v; o% o. J
  }' p2 T0 \- c. c$ F8 y7 h
                您也可以将总和放在case语句中,在case语句中评估其他条件,然后仅对条件为true的那些记录求和…
! |7 K( C" J2 W. K& N  SELECT m.member_id, m.teamname, / A, n1 B3 k+ X/ B3 H& b
    Sum(Case When r.track_Id = '$chosentrack' 7 a# N. y- \  \6 N8 k+ ~( ^7 O& @
         Then total_points Else 0 End) TotalChosenTrackPoints,
! z* Y7 V! y! D/ g0 q# U( R6 g# k    Sum(Case When r.track_Id < '$chosentrack'
  d" _2 W5 N6 J' m7 m! l         Then total_points Else 0 End) TotalLessThanChosenTrackPoints,
' P' V1 v! Z1 r0 k% e' d+ U    total_points as last_race_points  $ N' Y' z: N9 |1 [
FROM members m
: x2 S( Z) o/ i% p9 @' w    Join members_leagues l
1 _5 U1 P8 }1 Q% B' [: |       On l.member_id = m.member_id  7 |) u$ x* @7 C) k' H1 S3 n
    Join member_results r* _1 }' c0 M1 Y" A$ v, }
       On r.member_id = m.member_id
/ q* p* ~3 m& G& Z Where l.league_id = '$chosenleague'% |* ^# @; h3 J& J4 F2 ^
    And l.start_race = '$chosentrack'
$ k6 T5 h, x9 u3 t0 a Group By m.member_id# c: l+ }9 W4 \$ b' h! v1 o
Order By r.total_points Desc, 3 v: f" O' s; C8 \, \
     last_race_points  Desc, m.TeamName Desc
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则