In a sql server database, I am trying to return thegender with the most about of money mad ethrough bonuses. I therefore have a sub query to calculate the sum of bonuses made by each gender, another subquery to return the max and finally, my main query returns the gender with this max. However my code is not working.
SELECT E.Gender, maxx.mm
FROM HumanResources.Employee as E, (SELECT MAX(Bonus) as mm FROM (SELECT E.Gender, SUM(SP.Bonus) AS Bonus FROM HumanResources.Employee AS E, Sales.SalesPerson AS SP GROUP BY E.Gender) AS gen) AS maxxwhere E.Gender = gen.Gender;
The last line :where E.Gender = gen.Gender doesn’t seem to work as gen.Gender can’t be bound
Any help please
I am not a big fan of the
subquery(subquery(subquery(model, as it is often wasteful and usually difficult to parse / understand / re-write. Here is how I initially wanted to re-write it when I saw it:Another way (potentially more efficient depending on the plan, since you will eliminate all but one employee from the join – something that may happen above, but also might not):