SQL0802 - Data Conversion or Data Mapping Error

早过忘川 提交于 2019-12-24 14:34:04

问题


I'm am trying to write a query that calculates some numbers on the servers side, rather than after the data is pulled. I keep getting the SQL0802 error. I have tried a regular Sum as well as Double and float commands. I think the return is to long. I'm using SQL Squirrel so I went and removed the decimal place restriction to see if that would fix the problem. It is the "Gross Margin" calculation that is throwing it off. The rest of the calculations work fine. I appreciate any help i can get. This is just a portion of the code. I omitted the Where, Group By, and Order By sections for the sake of space:

Select  Distinct DB1.Tb1.STORE,
        DB1.Tb2.DATE_ID,

Sum (DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES) As "Total Sales",

Sum (DB1.Tb1.CUR_CASH_COST+DB1.Tb1.CUR_CHARGE_COST) As "Total Cost",

Sum ((DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES)-DB1.Tb1.CUR_CASH_COST+DB1.Tb1.CUR_CHARGE_COST)) As "Gross Profit",

Sum (((DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES)-(DB1.Tb1.CUR_CASH_COST+DB1.Tb1.CUR_CHARGE_COST))/(DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES)))As "Gross Margin"

回答1:


If the problem is divide-by-zero, you simply need to prevent the division from happening when the denominator is zero. The easiest way would be to sum the numerator and denominator separately, then divide after that happens:

       sum (
           DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES-
           DB1.Tb1.CUR_CASH_COST+DB1.Tb1.CUR_CHARGE_COST
       ) /
       sum (
           DB1.Tb1.CUR_CASH_SALES+DB1.Tb1.CUR_CHARGE_SALES
       ) as "Gross Margin"

Then you would only get a divide-by-zero if the denominator is zero for the entire category you are grouping on.

If it is still a problem, you will need to do something else in addition. Depending on what you want, you could:

  • Use your where clause to exclude groups with a zero denominator from your output.
  • Put a case statement around the entire calculation that checks if the denominator is zero before calculating. If it is zero, replace the calculation with whatever output makes sense (zero, null, etc.).



回答2:


If divide by zero is your problem, consider that there may be no point in including rows that have no sales.

Consider using a CASE expression to do division only when the sales are not zero, but use null when the sales are zero.



来源:https://stackoverflow.com/questions/14592470/sql0802-data-conversion-or-data-mapping-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!