使用SQL SELECT语句进行长算术运算

时间:2017-08-31 03:07:38

标签: sql sql-server

基本思路是我有3个单独的SELECT语句输出一个数字。我需要这些数字的百分比。所以问题看起来像这样:

(a.count_one + b.count_two) -
(b.count_two + c.count_three) / (a.count_one + b.Count_two) * 100

当我执行下面的代码时,我只得到第一个(a.count_one + b.count_two)的输出。但如果我注释掉/ (a.count_one + b.count_two)的第三部分,我成功地从(a.count_one + b.count_two) – (b.count_two + c.count_three)获得了正确的解决方案。

所以看来,对两个语句进行数学计算是很好的,但是当我抛出第三个语句时,它只是想要显示第一个问题的解决方案(a.count_one + b.count_two),但是甚至没有尝试计算(a.count_one + b.count_two) – (b.count_two + c.count_three)的解决方案了。我有点难过为什么。

Select
    (a.Count_one + b.Count_two) - 
    (b.Count_two + c.Count_three) / (a.Count_one + b.Count_two) * 100 
    as 'Final_Percentage' 
from 

(
select COUNT(v_Summary.ResourceID) AS Count_one
From [DB1].[dbo].[v_Summary]
) a,

(
select count([CN]) as Count_two
From [DB2].[dbo].[Computers] 
WHERE cn NOT IN (SELECT name0 FROM [DB1].[dbo].[v_system] where v_system.Client0 = '1')
) b,

(
select COUNT(v_Summary.ResourceID) AS Count_three
From [DB1].[dbo].[v_Summary]
Where Description like '%/Fail'
) c

并提供更多信息。数字的数学问题:

(54558 + 373) – (373 + 117) / (54558 + 373) * 100

或进一步解决:

(54931) - (490) / 55304 * 100 = 98.44%

2 个答案:

答案 0 :(得分:0)

COUNT函数返回int。当您划分两个int值时,SQL Server中的结果将再次为int。因此,490 / 553040。然后0 * 100再次0

将值转换为合适的类型,例如float

顺便说一下,

(54931) - (490) / 55304 * 100 

不等于~98.44,等于~54930.11399 你需要括号来得到你期望的结果:

((54931) - (490)) / 55304 * 100 

等于~98.43953421

因此,最终查询应如下所示:

Select
    ((a.Count_one + b.Count_two) - (b.Count_two + c.Count_three)) 
    / (a.Count_one + b.Count_two) * 100 
    as 'Final_Percentage' 
from 

(
select CAST(COUNT(v_Summary.ResourceID) AS float) AS Count_one
From [DB1].[dbo].[v_Summary]
) a,


(
select CAST(count([CN]) AS float) as Count_two
From [DB2].[dbo].[Computers] 
WHERE cn NOT IN (SELECT name0 FROM [DB1].[dbo].[v_system] where v_system.Client0 = '1')
) b,


(
select CAST(COUNT(v_Summary.ResourceID) AS float) AS Count_three
From [DB1].[dbo].[v_Summary]
Where Description like '%/Fail'
) c

答案 1 :(得分:0)

你也应该通过说

来得到正确的结果
Select
100.*(a.Count_one - c.Count_three) / (a.Count_one + b.Count_two)
as 'Final_Percentage' 
from ... -- unchanged subqueries, as supplied in your question 

通过将*100.向右移动到前面,您可以隐式地将第一个产品转换为浮动,然后类型将保持这种方式用于剩余的计算。另外,您可能已经注意到,我简化了公式,因为b.Count_two会从自身中减去,所以您可以将其完全删除。我没有测试过这个,但我很确定它会起作用。