用case语句修复除零错误

时间:2019-05-13 18:50:32

标签: sql-server

我继承了一些除以零错误的代码。

我不断收到错误,不确定是代码还是我将其放置在哪里。 应该添加还是替换该行?

尝试添加和替换此case语句: 当SUM(PREOP_MME)= 0时为CASE,然后0 ELSE SUM(PREOP_MME)/ SUM(COUNT_CASES)结束为PREOP_MME)。

SELECT 

PROCEDURE_NM
,SUM(PreOp_MME)     / SUM(COUNT_CASES) PreOp_MME
,SUM(IntraOp_MME)   / SUM(COUNT_CASES) IntraOp_MME 
,SUM(PostOp_MME / PostOp_LOS) PostOp_MME
,SUM(Discharge_MME) / SUM(COUNT_CASES) Discharge_MME
,SUM(TOTAL_OVERALL_MME) / SUM(COUNT_CASES) Overall_MME


FROM (

SELECT DISTINCT 

Spine.LOG_ID
,Spine.SERV_AREA_ID [Service Area ID]
,Spine.LOC_ID [Revenue Location ID] 
,Spine.PRIMARY_PHYS_ID [Provider ID]
,Spine.SURGERY_DATE
,Spine.COUNT_CASES
,Spine.PROCEDURE_NM
,Spine.PostOp_LOS

,(PreOp.SUM_SIG * PreOp.PreOp_MME)          AS PreOp_MME
,(IntraOp.SUM_SIG * IntraOp.IntraOp_MME)    AS IntraOp_MME
,(PostOp.SUM_SIG * PostOp.PACU_MME)         AS PostOp_MME
,DischMeds.DOSE_MME                 AS     Discharge_MME

,(PreOp.SUM_SIG * PreOp.PreOp_MME) + 
 (IntraOp.SUM_SIG * IntraOp.IntraOp_MME) + 
 (PostOp.SUM_SIG * PostOp.PACU_MME) + DischMeds.DOSE_MME as TOTAL_OVERALL

3 个答案:

答案 0 :(得分:2)

您应该检查除数(分母),而不是除数(分子)不等于0,因此对于第一列您可以尝试

SELECT 

    PROCEDURE_NM, 
    case when SUM(COUNT_CASES) = 0 
                  then 0 
                  else SUM(PreOp_MME)/ SUM(COUNT_CASES) end PreOp_MME,
    .....

答案 1 :(得分:1)

只需使用COALESCE

在此我以一个小的 demo 为例

SELECT id,
       SUM(`value1`) / SUM(`value2`) as _before,
       COALESCE (SUM(`value1`) / SUM(`value2`) , 0) as _after
FROM Table1
GROUP by id;

答案 2 :(得分:0)

谢谢您的回答。

当SUM(FIELD)= 0然后0 ELSE SUM(FIELD)/ SUM(FIELD)END AS为

时,我使用了这种情况

我的错误是因为我没有在每个实例中都考虑零,而仅是第一个。一定是时候回家了!