SQLserver遇到0作为除数咋办

WITH A AS (

SELECT COUNT

( NAME ) AS TRADITIONSUM 

FROM

ODBusiness.DBO.ONCONTRACT 

WHERE

DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 0 

AND 

  PMCSUM NOT IN ('0')

),

B AS (

SELECT COUNT

( NAME ) AS TRADITIONSUM 

FROM

ODBusiness.DBO.ONCONTRACT 

WHERE

DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 1 

AND 

  PMCSUM NOT IN ('0')

) SELECT

CAST((A.TRADITIONSUM - B.TRADITIONSUM) AS FLOAT) /(B.TRADITIONSUM) FROM

A,


用户K0035705 发布于 2020-12-7 13:07
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共5回答
最佳回答
0
AmyQLv6初级互助
发布于2020-12-7 13:12

WITH A AS (

SELECT COUNT

( NAME ) AS TRADITIONSUM 

FROM

ODBusiness.DBO.ONCONTRACT 

WHERE

DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 0 

AND 

  PMCSUM NOT IN ('0')

),

B AS (

SELECT COUNT

( NAME ) AS TRADITIONSUM 

FROM

ODBusiness.DBO.ONCONTRACT 

WHERE

DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 1 

AND 

  PMCSUM NOT IN ('0')

) SELECT case when B.TRADITIONSUM=0 then ' ' else

CAST((A.TRADITIONSUM - B.TRADITIONSUM) AS FLOAT) /(B.TRADITIONSUM) end FROM

A,


最佳回答
0
Doctor_WeiLv7中级互助
发布于2020-12-7 13:08

case when ,数据未0时特殊处理

最佳回答
0
krystal033Lv7高级互助
发布于2020-12-7 13:09

用where排除掉0值不行吗

  • zsh331 zsh331 NULLIF(B.TRADITIONSUM,0),一劳永逸
    2020-12-07 13:20 
最佳回答
0
snrtuemcLv8专家互助
发布于2020-12-7 13:09(编辑于 2020-12-7 13:24)
	WITH A AS (
		SELECT COUNT
			( NAME ) AS TRADITIONSUM 
		FROM
			ODBusiness.DBO.ONCONTRACT 
		WHERE
			DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 0 
		AND 
		  PMCSUM NOT IN ('0')
		),
		B AS (
		SELECT COUNT
			( NAME ) AS TRADITIONSUM 
		FROM
			ODBusiness.DBO.ONCONTRACT 
		WHERE
			DATEDIFF( MONTH, [INPUTTIME], GETDATE( ) ) = 1 
			AND 
		  PMCSUM NOT IN ('0')
		) SELECT
		case when B.TRADITIONSUM =0 then (A.TRADITIONSUM - B.TRADITIONSUM) AS FLOAT
		else CAST((A.TRADITIONSUM - B.TRADITIONSUM) AS FLOAT) /(B.TRADITIONSUM) end FROM
		A,
		B


  • zsh331 zsh331 NULLIF(B.TRADITIONSUM,0),另外你的case没有结束,肯定报语法错误;
    2020-12-07 13:20 
最佳回答
0
ZhanggggLv6见习互助
发布于2020-12-7 14:10

用case when或者是nullif()

  • 6关注人数
  • 381浏览人数
  • 最后回答于:2020-12-7 14:10
    请选择关闭问题的原因
    确定 取消
    返回顶部