如何将NULLIF与聚合函数一起使用

问题描述 投票:0回答:1

我正在使用SQL Management Studio2012。我遇到“遇到零除错误”错误。我知道这需要使用NULLIF,但不确定如何在查询中使用它。

这是我的查询

 select 
 Ward,
 LocalAuthority,
 Fiscal,
 DR,
 cast(DR*100.0 /SUM(DR) OVER(partition by localauthority,fiscal order by fiscal asc) as Decimal (10,2)) as [DR%]


from (

select  


Fiscal,
LocalAuthority,
Ward,

sum(case when code = 'DR' then 1 else 0 end) as DR


from 
[dbo].[Table]

 where datetimeofcall >='2014-04-01' 



 group by ward,localauthority,fiscal

 ) as A

我实际上已经问过这个问题,在此之前,一个好心人给出了很好的回答,但是那没有OVER()和SUM聚合函数,我陷入了语法混乱。我一直在尝试以下各种含义,但没有成功。

cast(DR*100.0 /NULLIF(SUM(DR,0),1) OVER(partition by localauthority,fiscal order by fiscal asc) as Decimal (10,2)) as [DR%]
sql ssms
1个回答
0
投票

使用Case Expression标识先前的0

SELECT Ward, LocalAuthority, Fiscal, DR,
CASE WHEN SUM(DR) OVER(PARTITION BY localauthority, fiscal ORDER BY fiscal asc) = 0 THEN 0 ELSE CAST(DR*100.0 / SUM(DR) OVER(PARTITION BY  localauthority,fiscal ORDER BY fiscal) AS Decimal (10,2)) END AS [DR%]
FROM (
      SELECT Fiscal, LocalAuthority, Ward, SUM(CASE WHEN code = 'DR' THEN 1 ELSE 0 END) AS DR
      FROM [dbo].[Table]
      WHERE datetimeofcall >='2014-04-01' 
      GROUP BY ward, localauthority, fiscal
     ) AS A
© www.soinside.com 2019 - 2024. All rights reserved.