Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count rows added today, yesterday...and other times

Tags:

sql

mysql

count

I was given good direction to solve a problem today from here but I got stuck in trying to follow this direction.

I would like to retrieve a count for all rows from a table for the past 30 days using my date field. I populate these fields using now() and they are in the format Y-m-d h:i:s.

  • I need a count for the rows added today, yesterday, 3 days ago...etc
  • I guess I can then use the above to get a count for each months?
  • Finally a count for the year, year before etc using the months as total?

I was hoping not to specify dates in my query and for the query to just be generic and work out counts relative to today. I was hoping also I could do it accurately too by taking into consideration different months have different number of days.

How can I get this count using just SQL? I then can use the result set as an array and parse this with PHP.

like image 908
Abs Avatar asked Mar 04 '09 16:03

Abs


People also ask

How can I get yesterday and today in SQL?

Discussion: To get yesterday's date, you need to subtract one day from today's date. Use GETDATE() to get today's date (the type is datetime ) and cast it to date . In SQL Server, you can subtract or add any number of days using the DATEADD() function.

How do I count unique rows?

We can use SQL Count Function to return the number of rows in the specified condition. The syntax of the SQL COUNT function: COUNT ([ALL | DISTINCT] expression); By default, SQL Server Count Function uses All keyword.

Why is Count 1 faster than count (*)?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

Which all function is used to count the number of rows?

The SQL COUNT( ) function is used to return the number of rows in a table.


2 Answers

Number of records inserted yesterday:

select count(*) from mytable where date(myfield)=date(date_sub(now(),interval 1 day));

For the year:

select count(*) from mytable where year(myfield)=year(now());

And so on...

like image 194
kyku Avatar answered Sep 30 '22 11:09

kyku


Look into MySQLs DATE_ADD and DATE_SUB function it will give you what your looking for.

like image 27
Hawk Kroeger Avatar answered Sep 30 '22 11:09

Hawk Kroeger