简体   繁体   中英

Counting non-zero values in sql

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.

Use NULLIF to change zero to NULL, count ignores 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;

You can probably remove the WHERE clause too with this group to improve performance
OR conditions often run badly because of matching a good index

Using HAVING (as per other answers) will remove any rows where all 3 aggregates are zero which may or may not be useful for you. You can add this if you want. Saying that, the WHERE implies that at least one row has non-zero values so you don't need both WHERE and HAVING clauses

Putting filter predicate[s] inside of a Sum() function with a case statement is a useful trick anytime you need to count items based on some predicate condition.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM