我正在使用SQL Server 2008。
我正在尝试在一些基本查询中做一些基本的数学运算。我需要加上胜利,损失,总数和百分比。我通常会询问原始数字,然后在将查询返回页面后再进行计算。我想让SQL Server有机会更努力地工作。
我想做的是这样的事情:
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
这就是我现在正在做的事情:
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
在查询中进行简单数学计算的最简单,最干净的方法是什么?
* 编辑:*
虽然我得到了一些很好的答案,但我没有得到我想要的东西。
我将计算的分数是针对特定团队的,因此,我的结果必须是这样的:
TeamID Team Wins Losses Totals
1 A's 5 3 8
2 Bee's 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部分是问题所在。如何将这两个结果集组合在一起?
答案 0 :(得分:10)
一种方法是将查询包装在外部查询中:
SELECT TotalWins,
TotalLosses,
TotalWins + TotalLosses as TotalPlays,
TotalPlays / TotalWins as PctWins
FROM
( 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
FROM ...
)
另一种方式(由@Mike Christensen建议)是使用Common Table Expressions (CTE):
; WITH Calculation AS
( 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
FROM ...
)
SELECT TotalWins,
TotalLosses,
TotalWins + TotalLosses as TotalPlays,
TotalPlays / TotalWins as PctWins
FROM
Calculation
旁注:不知道这是否意味着SQL-Server中的任何性能差异,但您也可以写下这些总和:
SUM(case when vote = 1 then 1 else 0 end)
作为计数:
COUNT(case when vote = 1 then 1 end) --- the ELSE NULL is implied
答案 1 :(得分:4)
试
select a, b, a+b as total
from (
select
case ... end as a,
case ... end as b
from realtable
) t
答案 2 :(得分:3)
要回答第二个问题,这是您提出的修正语法的代码:
SELECT
T.TeamID,
T.Team,
V.TotalWins,
V.TotalLosses,
PctWins = V.TotalWins * 100 / CAST(V.TotalWins + V.TotalLosses AS float)
FROM Teams T
JOIN (
SELECT
TeamID,
SUM(case when vote = 1 then 1 else 0 end) as TotalWins,
SUM(case when vote = 0 then 1 else 0 end) as TotalLosses
FROM Votes
GROUP BY TeamID
) as V on T.TeamID = V.TeamID
注意内部选择的括号。
答案 3 :(得分:2)
如果你不止一次做这种事情来创建一个视图,它可能会有所帮助......
CREATE VIEW [Totals]
SELECT
SUM(case when T.vote = 1 then 1 else 0 end) as TotalWins,
SUM(case when T.vote = 0 then 1 else 0 end) as TotalLosses,
T.SomeGroupColumn
FROM SomeTable T
GROUP BY T.SomeGroupColumn