我试图计算每个列大于零的总次数,按驱动程序名称分组.现在我有;
SELECT drivername,COUNT(over_rpm) AS RPMViolations,COUNT(over_spd) AS SpdViolations,COUNT(brake_events) AS BrakeEvents FROM performxbydriverdata WHERE over_rpm > 0 OR over_spd > 0 OR brake_events > 0 GROUP BY drivername
这给了我所有的非零值,但我得到一个显示为:
>鲍勃史密斯62 62 62
>内森琼斯65 65 65
>等
我试图在每个单独的值中计算非零值.每个违规都应该单独分组.
解决方法
使用NULLIF将零更改为NULL,count忽略NULL
SELECT drivername,COUNT(NULLIF(over_rpm,0)) AS RPMViolations,COUNT(NULLIF(over_spd,0)) AS SpdViolations,COUNT(NULLIF(brake_events,0)) AS BrakeEvents FROM performxbydriverdata GROUP BY drivername;
您也可以使用此组删除WHERE子句以提高性能
由于匹配好的索引,OR条件经常运行得很糟糕
使用HAVING(根据其他答案)将删除所有3个聚合为零的行,这些行可能对您有用,也可能对您没用.如果需要,您可以添加此项.说,WHERE意味着至少有一行具有非零值,因此您不需要WHERE和HAVING子句