Ctr

Slugging Average

For this challenge, imagine that you are an analyst for the MLB working to identify the greatest batters in baseball. You have a table of players' batting attempts in a table called plate_appearances.


plate_appearances
column_name type reference
id
INTEGER
NULL
batter_id
INTEGER
batters.id
strikes
INTEGER
NULL
balls
INTEGER
NULL
outcome
VARCHAR
NULL

Each row holds the outcome of batting attempts, i.e. whether they got on base, or got out, etc. To see all the distinct values that the outcome column can hold, you know how to write that query! (hint)

Calculate the slugging average for each player. The slugging average is basically a weighted average for how good a batter is. It is calculated as the number of total bases earned divided by the number of at-bats. In the numerator, "total bases" means 1 base earned if they reached 1st base, 2 bases earned if they reached 2nd base, 3 bases earned if they reached 3rd base, and 4 bases earned if they hit a home run. Everything else is worth 0. The number of "at-bats" in the denominator is the sum total of plate appearances that do not result in a walk, getting hit by a pitch, catcher interference, sacrifice bunt, or sacrifice fly.

Select each batter_id and calculate their slugging average (name that slugging_average). Order the rows in descending order by slugging_average.

Division with INTEGERs can be a little surprising, unlike division with NUMERICs.

SELECT
  2 / 3 AS integer_division,
  2.0 / 3.0 AS numeric_division;
integer_division
INTEGER
numeric_division
NUMERIC
0
0.66666666666666666667

© 2022 Andrew Carlson. All rights reserved.

batter_id
INTEGER
slugging_average
NUMERIC
1
1048
0.77777777777777777778
2
8255
0.70967741935483870968
3
5594
0.68965517241379310345
4
4989
0.66666666666666666667
5
8492
0.65217391304347826087
6
6551
0.65217391304347826087
7
2139
0.57142857142857142857
8
6258
0.54166666666666666667
9
8382
0.46666666666666666667
10
5281
0.43750000000000000000
11
1528
0.42424242424242424242
12
2037
0.39393939393939393939
13
4268
0.38709677419354838710
14
8929
0.21052631578947368421
15
5497
0.20588235294117647059
15 rows

You haven't solved this challenge yet!
Are you sure you want to reveal the answer?