SQL如何使用收集的SUM值计算行值

时间:2017-12-22 03:09:04

标签: mysql sql

mlb_pitchers表

+------+-----------+-----------+-----+-----+
| year | playerID  | nameLast  | IP  | ER  |
+------+-----------+-----------+-----+-----+
| 1903 | mathech01 | Mathewson | 366 |  92 |
| 1903 | youngcy01 | Young     | 341 |  79 |
| 1904 | mathech01 | Mathewson | 367 |  83 |
| 1904 | walshed01 | Walsh     | 110 |  32 |
| 1904 | youngcy01 | Young     | 380 |  83 |
| 1905 | mathech01 | Mathewson | 338 |  48 |
| 1905 | walshed01 | Walsh     | 136 |  33 |
| 1905 | youngcy01 | Young     | 320 |  65 |
| 1906 | mathech01 | Mathewson | 266 |  88 |
| 1906 | walshed01 | Walsh     | 278 |  58 |
| 1906 | youngcy01 | Young     | 287 | 102 |
+------+-----------+-----------+-----+-----+

首先,要获得1903年至1906年投手的每位投手的IP和ER总和,但也必须在1903年投球。

SELECT
  playerID,
  nameLast,
  SUM(IP),
  SUM(ER)
FROM mlb_pitchers
WHERE year >= 1903
AND year <= 1906
GROUP BY playerID,
         nameLast
HAVING SUM(CASE
  WHEN year = 1903 THEN 1
  ELSE 0
END) > 0

输出

+-----------+-----------+---------+---------+
| playerID  | nameLast  | SUM(IP) | SUM(ER) |
+-----------+-----------+---------+---------+
| mathech01 | Mathewson |    1337 |     311 |
| youngcy01 | Young     |    1328 |     329 |
+-----------+-----------+---------+---------+

我想做的是,并且无法弄清楚要添加到SQL的内容,是添加一个输出列(新行值),该列使用SUM值来计算投手的ERA。 ERA = ER / IP * 9.因此输出应如下所示:

+-----------+-----------+---------+---------+------+
| playerID  | nameLast  | SUM(IP) | SUM(ER) | ERA  |
+-----------+-----------+---------+---------+------+
| mathech01 | Mathewson |    1337 |     311 | 2.09 |
| youngcy01 | Young     |    1328 |     329 | 2.23 |
+-----------+-----------+---------+---------+------+

2 个答案:

答案 0 :(得分:4)

添加一个额外的输出列,用于执行ERA的计算,如下所示:

SELECT playerID, nameLast, SUM(IP), SUM(ER),  (SUM(ER) / SUM(IP)) * 9.0 as ERA
FROM mlb_pitchers 
WHERE year >= 1903 AND year <= 1906 
GROUP BY playerID, nameLast 
HAVING SUM(CASE WHEN year = 1903 THEN 1 ELSE 0 END) > 0 

答案 1 :(得分:2)

SELECT playerID, nameLast, SUM(IP), SUM(ER),
   9.0*SUM(ER)/Sum(IP) ERA,
FROM mlb_pitchers 
WHERE year >= 1903 AND year <= 1906 
GROUP BY playerID, nameLast 
HAVING SUM(CASE WHEN year = 1903 THEN 1 ELSE 0 END) > 0