Hourly counting based on start time and end time data
P粉283559033
2023-08-30 15:53:41
<p>In the table, the data is in timestamp format but I am sharing it in time(start_at) and time(end_at) format. </p>
<p>Table structure:</p>
<pre class="brush:php;toolbar:false;">id, start_at, end_at
1, 03:00:00, 06:00:00
2, 02:00:00, 05:00:00
3, 01:00:00, 08:00:00
4, 08:00:00, 13:00:00
5, 09:00:00, 21:00:00
6, 13:00:00, 16:00:00
6, 15:00:00, 19:00:00</pre>
<p>For the result, we need to count the number of active ids between the start_at and end_at times. </p>
<pre class="brush:php;toolbar:false;">hours, count
0, 0
1, 1
twenty two
3, 3
4, 3
5, 2
6, 1
7, 1
8,1
9, 2
10, 2
11, 2
12, 2
13, 3
14, 2
15, 3
16, 2
17, 2
18, 2
19,1
20,1
21,0
22,0
23, 0</pre></p>
or
or
The first query returns the hour column in time format, while the second query returns this column in numeric form. Choose the variant that is safe for you.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5a77b6e3158be06c7a551cb7e64673de