SQL分割两个SUM()函数

时间:2018-06-06 13:20:00

标签: sql sql-server

Name  | CountWin | CountFail | Failure% |
---------------------------------
TypeA |   100    |   50      |    50    |
TypeB |   100    |   5       |     5    |
TypeC |   100    |   100     |   100    |
TypeD |   100    |    0      |     0    |

我正在尝试用sql创建上面的表。结果不是我所期望的。 结果如下

 Name  | CountWin | CountFail | Failure% |
---------------------------------
TypeA |   100    |   50      |     0    |
TypeB |   100    |   5       |     0    |
TypeC |   100    |   100     |     0    |
TypeD |   100    |    0      |     0    |

sql代码:

INSERT INTO #my_temp_table
  select type, date, CountWin, CountFail from myTable

select type, SUM(CountWin) as CountWin, SUM(CountFail) as CountFail, (((SUM(CountFail) / SUM(CountWin)) * 100) as Failure%
FROM #my_temp_table
WHERE date > DATEADD(day, -7, getdate())
GROUP BY type, date

只是想知道为什么我的(((SUM(CountFail)/ SUM(CountWin))* 100没有返回正确的值

2 个答案:

答案 0 :(得分:3)

您的数据库可能正在执行整数除法。只需将计算结果如下:

select type, date, SUM(CountWin) as CountWin, SUM(CountFail) as CountFail,
      SUM(CountFail) * 100.0 / NULLIF(SUM(CountWin), 0) as Failure_percent
FROM #my_temp_table
WHERE date > DATEADD(day, -7, getdate())
GROUP BY type, date;

注意:

  • 您的where子句正在使用getdate()上的时间。您更有可能:date > dateadd(day, -7, cast(getdate() as date))
  • NULLIF()阻止除以0。
  • 你的计算是一个比例,而不是百分比。也许你打算:SUM(CountFail) * 100.0 / NULLIF(SUM(CountWin + CountFail))

答案 1 :(得分:0)

你必须将它投射到浮动

    INSERT INTO #my_temp_table
    select type, date, CountWin, CountFail from myTable

    select type, SUM(CountWin) as CountWin, SUM(CountFail) as 
    CountFail, (((SUM(CountFail) / CAST(SUM(CountWin) as float)) * 100) as 
    Failure%
    FROM #my_temp_table
    WHERE date > DATEADD(day, -7, getdate())
    GROUP BY type, date