sqlsqlite

Aggregating both null and not null counts in a single query


What is an elegant way to get a summary of records with both Null and non-Null values in a particular field/column, in a single query?

I'm using this, sort of works but the non-Null has to be calculated from the results. Table in question is called 'BatchHeaders', the concerned field is 'Updated', a 'Date' field, considered 'Not Updated' when Null.

WITH TableA as (
  SELECT 
    count(Id) as Total,
    1 as Idx 
  FROM BatchHeaders
)
SELECT 
  TableA.Total, 
  count(Id) as NotUpdated,
  1 as Idx 
FROM BatchHeaders 
JOIN TableA on TableA.IDX=Idx 
WHERE Updated is NULL;

Solution

  • COUNT(updated) already counts the number if NOT NULL values...

    SELECT 
       COUNT(*)                    AS total,
       COUNT(updated)              AS updated,
       COUNT(*) - COUNT(updated)   AS not_updated 
    FROM
       BatchHeaders