Nested selects when dealing with calculated columns

82 Views Asked by At

I'm trying to write a nested select statement that returns a single row that emulates the batting average from this site https://www.espn.com/mlb/team/stats/_/name/hou/season/2005/seasontype/2/table/batting/sort/avg/dir/desc. I encountered a divide by zero error that I used (Case when AB=0 then 1 else AB end) for "at bats" which works but I get 6 rows instead of 1.

select namefirst + namelast as 'Name', (h\*1.0)/(Case when AB=0 then 1 else AB end) as 'BA' FROM vwPlayersBatting
WHERE  'BA' = (SELECT MAX('BA')
FROM vwPlayersBatting
WHERE teamID = 'HOU' and yearID = 2005)
and teamID = 'HOU' and yearID = 2005 and AB \> 400

I'm basing the top statement off similar statements like the one below that have worked such as for homeruns

 select namefirst + namelast as 'Name', HR FROM vwPlayersBatting
 WHERE HR = (SELECT MAX(HR)
 FROM vwPlayersBatting
 WHERE teamID = 'HOU' and yearID = 2005)
 and teamID = 'HOU' and yearID = 2005
1

There are 1 best solutions below

0
MatBailie On

You can order by a calculated column, and then restrict the results to the top 1 (with ties in as multiple batters are equal top).

SELECT TOP 1 WITH TIES
  namefirst + namelast   AS name, 
  (h*1.0)/NULLIF(AB, 0)  AS BA
FROM
  vwPlayersBatting
WHERE
      teamID = 'HOU'
  AND yearID = 2005
  AND AB     > 400
ORDER BY
  2 DESC