SQL计算百分比

时间:2015-09-16 04:10:18

标签: sql

我在表格中有四列。

+------+-------+------------+---------------+
| Year | Month | OrderCount | SaleCount2015 |
+------+-------+------------+---------------+
| 2015 |   1   |    876     |     453       |
| 2015 |   2   |    764     |     548       |
| 2015 |   3   |    951     |     632       |
| 2015 |   4   |    ...     |     ...       |
+------+-------+------------+---------------+

我想计算每个月的SalePercentage,但结果会返回0。我使用以下SQL查询。

Select Year, 
       Month, 
       OrderCount, 
       SaleCount, 
       SaleCount/OrderCount AS SalePercentage
From TableName

有人能告诉我这个查询的问题吗?谢谢。

4 个答案:

答案 0 :(得分:0)

SELECT Year, Month, OrderCount, SaleCount,
    CAST (SaleCount AS FLOAT) / CAST(OrderCount AS FLOAT) AS SalePercentage
FROM TableName

您正在使用整数除法,因此5/10将为0,但5.0/10.0将为0.5

答案 1 :(得分:0)

如果您使用sql server

如果你除了整数,那么你得到整数作为结果;

将一个或两个列值转换为floatdouble

cast(SaleCount as float) /OrderCount AS SalePercentage

(SaleCount*1.0)/OrderCount AS SalePercentage

最好检查OrderCount是否为zero

case when OrderCount = 0 then 0
else (SaleCount*1.0)/OrderCount end AS SalePercentage 

演示 sqlfiddle

答案 2 :(得分:0)

使用资金类型进行财务计算......

SELECT Year, Month, OrderCount, SaleCount, IIF(OrderCount  = 0, 0, CAST(SaleCount AS MONEY)/CAST(OrderCount AS MONEY)) AS SalePercentage FROM TableName

答案 3 :(得分:0)

无论您使用哪种数据库。您的结果不显示百分比,而是一小部分。如果你将它乘以100,它将被解决:

Select Year, 
       Month, 
       OrderCount, 
       SaleCount, 
       (SaleCount*100)/OrderCount AS SalePercentage
From TableName