为什么我除以百分比时无法正确计算百分比?

时间:2020-04-17 18:16:27

标签: sql sql-server tsql group-by

我正在尝试查看支付LL的客户百分比和支付LP的客户百分比。例如,我在LL中有1个客户,在LP中有1个客户,因此百分比在Cust_LL_Pct和Cust_LP_Pct中应为50%。我尝试使用ISNULL,并将其设置为0,但这并不能解决问题。 “ Pct列”仅给出0和1之间的值。 enter image description here

[SELECT
 b.country_IBS AS Country_IBS_LL
,b.Sku AS SKU_LL
,b.TY_Sales_USD_LL 
,b.TY_Qty_LL
,b.TY_Sales_USD_LL / (b.TY_Qty_LL) AS ASP_LL
,b.Customer_Count_LL
,a.country_IBS AS Country_IBS_LP
,a.Sku AS SKU_LP
,a.Total_LP_Sales
,a.Total_LP_Qty
,a.Total_LP_Sales / a.Total_LP_Qty AS ASP_LP
,a.Customer_Count_LP
,SUM(ISNULL(b.Customer_Count_LL,0) + ISNULL(a.Customer_Count_LP,0)) AS SKU_Total_Customer
,ISNULL(b.Customer_Count_LL,0) / SUM(ISNULL(b.Customer_Count_LL,0) + ISNULL(a.Customer_Count_LP,0)) AS Cust_LL_Pct
,ISNULL(a.Customer_Count_LP,0) / SUM(ISNULL(b.Customer_Count_LL,0) + ISNULL(a.Customer_Count_LP,0)) AS Cust_LP_Pct
--INTO #temp6
FROM #temp2 a
FULL JOIN #temp5 b
ON a.Sku = b.Sku
AND a.country_IBS = b.country_IBS
GROUP BY
b.country_IBS
,b.Sku
,b.TY_Sales_USD_LL
,b.TY_Qty_LL
,b.TY_Sales_USD_LL / b.TY_Qty_LL 
,b.Customer_Count_LL
,a.country_IBS
,a.Sku
,a.Total_LP_Sales
,a.Total_LP_Qty
,a.Total_LP_Sales / a.Total_LP_Qty 
,a.Customer_Count_LP][1]

1 个答案:

答案 0 :(得分:2)

问题是整数除法。当两个操作数均为整数时,SQL Server产生整数结果:例如,3/2产生1,而不是1.5

您需要对操作强制使用十进制上下文,例如,通过乘以(虚拟)十进制值,例如:

1.0 * b.TY_Sales_USD_LL / b.TY_Qty_LL AS ASP_LL

我不建议将isnull(..., 0)用于除法的正确操作数:如果该值实际上是null,则将除以0,这是一个致命错误。另一方面,除以null会得到null,这不会失败,而且似乎更相关。