下面的这句话为我提供了一些我需要的数据。
select TankName, COUNT(*) as Tanks, sum(Battles) as Battles,
SUM(victories) as Victories
from MemberTanks
where Tier = 9 and Class = 'Medium'
group by TankName
order by Tanks desc
我想在结果集中显示胜利的百分比,但我不知道该怎么做。我试过......
select TankName, COUNT(*) as Tanks, sum(Battles) as Battles,
SUM(victories) as Victories, SUM(Victories)/SUM(Battles) as Percentage
from MemberTanks
where Tier = 9 and Class = 'Medium'
group by TankName
order by Tanks desc
...但每一行的回报率为“0”。
我怎样才能最好地获得这个价值?
答案 0 :(得分:4)
当你计算百分比列,因为SUM(X)返回一个INT值,结果会变为floored,因此返回0作为floored result
将SUM(胜利)乘以像1.0这样的十进制值(以便将一个操作数转换为十进制/数字)然后你会得到正确的结果。
试试这个:
SELECT TankName,
COUNT(*) as Tanks,
SUM(Battles) as Battles,
SUM(victories) as Victories,
SUM(victories) * 1.0/ SUM(Battles) AS Percentage
FROM MemberTanks
WHERE Tier = 9
AND Class = 'Medium'
GROUP BY TankName
ORDER BY Tanks desc
此外,如果您使用的是SQL Server 2005或更高版本,则可以使用如下所示的CTE减少calculate.computations:
WITH qry AS
(
SELECT TankName,
COUNT(*) as Tanks,
SUM(Battles) as Battles,
SUM(victories) as Victories
FROM MemberTanks
WHERE Tier = 9
AND Class = 'Medium'
GROUP BY TankName
)
SELECT a.*,
Victories * 1.0 / Battles AS Percentage
FROM qry a
ORDER BY Tanks DESC
答案 1 :(得分:2)
试试这个 -
SUM(Convert(float, Battles))/ Sum(Convert(float, Victories))
请参阅MSDN:
返回参数的数据类型 具有更高的优先权。更多 信息,请参阅数据类型优先级 (处理SQL)。
如果整数除数除以 一个整数除数,结果是一个 具有任何小数部分的整数 截断的结果。