Home > Back-end >  how to count data occurrence between certain DateTime range in mysql
how to count data occurrence between certain DateTime range in mysql

Time:10-04

I am sorry for this kind of newbie question, but it is quite hard for me. My MySQL table holds high-frequency stock prices. On each trading date, data starts from day 1 18:00 to day 2 17:00. I want to count the data occurrence for each trading day between the above trading hour. I know how to count for a single day just as following code

SELECT COUNT(*) FROM table WHERE date BETWEEN '2021-08-25 18:00:00' AND '2021-08-26 17:00:00' 

But how to count all the days in the table?

My table looks like this: enter image description here

What I want to looks like this: enter image description here

Thanks in advance.

CodePudding user response:

Appreciate that your "day" starts at 6pm. So, we can normalize each datetime by subtracting 18 hours, and then aggregate:

SELECT DATE(date - INTERVAL 18 HOUR), COUNT(*) AS cnt
FROM yourTable
GROUP BY 1;
  • Related