Count between dates and operate between rows – SQL

All we need is an easy explanation of the problem, so here it is.

I try to count elements between dates and operate between rows agnostically. As an example, suppose the month starts from day 2 until day 2 of next month. The table has fields {timestamp, status} and the status field has 3 different types. I do not know how to make it count between dates. Also, I would like to have the percentage of statuses.

Thank you for the help sincerely.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

WHERE timestamp >= '2021-04-02'
  AND timestamp  < '2021-04-02' + INTERVAL 1 MONTH
  AND status = "done"

(If you need to discuss further, please provide SHOW CREATE TABLE and more details about the desired query.)

And this index may help with performance:

INDEX(status, timestamp)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply