Skip to content
Advertisement

SQL Query count with group by and having at least one date filled

I need to write a sql query where I count number of employees who are not featured. Each employee can have multiple records with member comments. If they are featured then the feature date will have date otherwise will have null value. I want to ignore those who are have been featured atleast once (will have a date associated in the feature date column)

For example:

Empid   comment     featuredate
101      cool       null
101      bad        2/2/2020
102      nice       null
102      not nice   null

so my query should return only empid 102 as they are not featured atleast once.

What I tried?

I tried group by along with having, but stuck there.

Advertisement

Answer

You can use aggregation:

select empid
from t
group by empid
having max(featuredate) is null;

Note: This assumes that all employees are in your table. If not, use not exists:

select e.*
from employees e
where not exists (select 1
                  from features f
                  where f.empid = e.empid and f.featuredate is not null
                 );

If you want only the count, you can use either as a subquery. Or just use select count(*) with the second query.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement