2015-09-16 205 views
-1

我在表中有四列。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 

任何人都可以告訴我這個查詢的問題嗎?謝謝。

+0

爲每一行百分比返回0? – ddw147

+1

你使用了什麼數據庫? –

+0

你使用'sql server'嗎? – Praveen

回答

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

您正在使用整數除法所以5/100,但5.0/10.00.5

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

0

使用類型金融計算...

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

貨幣和IIF是產品特定的功能 - 哪些dbms? (沒有指定有問題的dbms。) – jarlh

+0

對不起!對於沒有指定。 MSSQL 2012和更高版本,這將是... – Esty

0

無論您使用的數據庫。你的結果不是顯示百分比,而是一小部分。如果您將乘以100它將被解決:

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