I am using SQL Server 2008.
I am trying to do some basic math in some basic queries. I need to add winnings, losses, total and percent. I usually request raw numbers, and then do the calculations when I return my request to the page. I would like to give SQL Server the ability to work a little harder.
I want to do something like this:
SELECT SUM(case when vote = 1 then 1 else 0 end) as TotalWins,
SUM(case when vote = 0 then 1 else 0 end) as TotalLosses,
TotalWins + TotalLosses as TotalPlays,
TotalPlays / TotalWins as PctWins
Here is what I am doing now:
SELECT SUM(case when vote = 1 then 1 else 0 end) as TotalWins,
SUM(case when vote = 0 then 1 else 0 end) as TotalLosses,
SUM(case when vote = 1 then 1 else 0 end) + SUM(case when vote = 0 then 1 else 0 end) as Votes
What is the easiest, cleanest way to do simple math calculations like this in a query?
* EDIT: *
While I got great answers, I didn't get what I was looking for.
The ratings that I will calculate are for a specific team, so my results should be as follows:
TeamID Team Wins Losses Totals
1 A 5 3 8
2 Bee 7 9 16
3 Seas 1 3 4
SELECT T.TeamID,
T.Team,
V.TotalWins,
V.TotalLosses,
V.PctWins
FROM Teams T
JOIN
SELECT V.TeamID,
SUM(case when vote = 1 then 1 else 0 end) as V.TotWin,
SUM(case when vote = 0 then 1 else 0 end) as V.TotLoss
FROM Votes V
GROUP BY V.TeamID
, , . , JOIN - . ?