Eli
Eli

Reputation: 35

SQL - Counting the number of users

I have written an sql code that return the number of cars per user.

SELECT count(car_name), id
FROM cars
WHERE date BETWEEN DATE("2013-01-01") AND DATE("2016-12-31")
GROUP BY 2
HAVING id > 2

The purpose of this code is to count the number of users within a specific time frame who have had at least 2 cars. However. the code above returns the following table

f0_ -- id
2  -- abdjdi23
3 --- jfhdfi123
2 ---- djndf33

But instead of this table, I just need it to return how many of the users have at least 2 cars or more. What should add to this code to work?

Thanks in advance

Upvotes: 0

Views: 98

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269873

Use two levels of aggregation:

select count(*)
from (SELECT count(*), id
      FROM cars
      WHERE date BETWEEN DATE('2013-01-01') AND DATE('2016-12-31')
      GROUP BY 2
      HAVING count(*) >= 2
     ) x

Upvotes: 2

Related Questions