Search code examples
mysqldatecountwhere-clausehour

MYSQL how to count how many hours where data exists


I am trying to count how many hours of the day there is data in the database.

I use this query:

SELECT
HOUR(date) AS `hour`, COUNT(date)
FROM fb_posts 
WHERE DATE(date) = CURDATE() - INTERVAL 1 DAY
GROUP BY hour

I got the query from here

example:

hour           COUNT(date)
00             55
01             2
02             33

Now I want calculate how many hours there was data? Above example should output value 3, because there was data at hour 00, 01 and 02

something would like to add COUNT(hour)like this:

SELECT
HOUR(date) AS `hour`, COUNT(date)**,COUNT(hour)**
FROM fb_posts 
WHERE DATE(date) = CURDATE() - INTERVAL 1 DAY
GROUP BY hour

Solution

  • select count(*) 
    from
    (
      SELECT HOUR(date) AS hour
      FROM fb_posts 
      WHERE DATE(date) = CURDATE() - INTERVAL 1 DAY
      GROUP BY hour
    ) tmp