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
.
count
for the rows added
today, yesterday, 3 days ago...etccount
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
.
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.
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.
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.
The SQL COUNT( ) function is used to return the number of rows in a table.
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...
Look into MySQLs DATE_ADD and DATE_SUB function it will give you what your looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With