13

I am trying to count total number of times that each individual column is greater than zero, grouped by the driver name. Right now I have;

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

This gives me all of the non-zero values but I get a display as:

  • Bob Smith 62 62 62
  • Nathan Jones 65 65 65
  • etc.

I'm trying to get a count of non-zeros in each individual values.. each violation should be grouped separately.

4

2 回答 2

27

使用 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 子句以提高性能,
或者由于匹配良好的索引而导致条件经常运行不佳

使用 HAVING (根据其他答案)将删除所有 3 个聚合都为零的任何行,这可能对您有用也可能没有用。如果你愿意,你可以添加这个。话虽如此,WHERE 意味着至少一行具有非零值,因此您不需要同时使用 WHERE 和 HAVING 子句

于 2013-05-27T14:16:11.040 回答
8

每当您需要根据某些谓词条件对项目进行计数时,将过滤谓词 [s] 放在带有 case 语句的 Sum() 函数中是一个有用的技巧。

Select DriverName,
    Sum(case When over_rpm > 0 Then 1 Else 0 End) OverRpm,
    Sum(case When over_spd > 0 Then 1 Else 0 End) OverSpeed,
    Sum(case When brake_events > 0 Then 1 Else 0 End) BrakeEvents,
    etc.
FROM performxbydriverdata
Group By DriverName
于 2013-05-27T14:18:05.560 回答