0

I have an SQL Table which stores some data and a date (e.g. yyyymmdd) and a time (e.g. hhmmss). Now I need to select a count of the number of entries for every hour of the day.

  • First count of entries will be: 000000 til 005959
  • Second will be: 010000 til 015959

Is it possible to make this with a single select and then have an array of 24 count results? Otherwise I will need to create 24 selects to get all the data I want.

5
  • Mysql or sql-server ? Commented Jun 16, 2016 at 16:23
  • what did you try so far? Commented Jun 16, 2016 at 16:25
  • This is where you should use a tally or numbers table as the main table in your query. Commented Jun 16, 2016 at 16:26
  • mysql, did not try anything because I dont know how to do it. I would create 24 individual querys, but I know that this is not a good solution. Commented Jun 16, 2016 at 16:29
  • 1
    select hour (time_column), count (*) from table group by hour(time_column) Commented Jun 16, 2016 at 16:41

3 Answers 3

1

Use group by function. Another option is to create fields for hour, minutes and seconds. It will duplicate data, but there is no problem.

CREATE TABLE test(id int, date varchar(8), time varchar(6)); INSERT INTO test VALUES(1,'20160616','015959'); INSERT INTO test VALUES(2,'20160616','015959'); INSERT INTO test VALUES(3,'20160616','025959'); SELECT count(substr(time,1,2)), test.date FROM test GROUP BY date, substr(time,1,2); 

Output:

count(substr(time,1,2)), date '2', '20160616' '1', '20160616' 

If you have a TIME column, just use:

 SELECT count(hour(time)), test.date FROM test GROUP BY date, hour(time); 

If you don't need to have this count by date, just remove from select and group by clauses.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you can just use the HOUR function. I don't use MYSQL, but it looks like it has this feature. Might check the syntax on it.

SELECT HOUR(TheTimeField), COUNT(*) FROM TheTable GROUP BY HOUR(TheTimeField) ORDER BY HOUR(TheTimeField) 

Comments

0
select hour (time_column), count (*) from table group by hour(time_column) 

http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_hour

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.