Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql date show results today/yesterday/week

I am retrieving data from a table and show the total SUM of entries. What I want to do is to show the total SUM of entries made on today's date, yesterday and this month. The table is using the unix timestamp format (e.g. 1351771856 for example).

Currently I am using this line to show todays results:

AND comment_date > UNIX_TIMESTAMP() - 24 * 3600";

but that gives me just the entries for the last 24 hours.

Example: So let's say its Friday, 17:00 PM - it gives me the count from Thursday 17:00 PM to Friday 17:00 PM

What I want is to get the results for

  • Thursday 00:00:00 - 23:59:59 (yesterday in this case)
  • the results for today (00:00:00 - 23:59:59)
  • and last week, results that start on Monday, 00:00:00 until "today" (in this case Friday).

I couldn't find a way in the MySQL documentation to achieve this.

like image 454
Georgi Grancharov Avatar asked Nov 02 '12 09:11

Georgi Grancharov


1 Answers

This mysql code should work for you:

// Today
AND DATE(from_unixtime(comment_date)) = CURRENT_DATE

// Yesterday
AND DATE(from_unixtime(comment_date)) =  DATE_SUB(CURRENT_DATE,INTERVAL 1 DAY)

// This week
AND YEARWEEK(from_unixtime(comment_date), 1) =  YEARWEEK(CURRENT_DATE, 1)

// This month
AND YEAR(from_unixtime(comment_date)) = YEAR(CURRENT_DATE)
AND MONTH(from_unixtime(comment_date)) = MONTH(CURRENT_DATE)
like image 194
vinculis Avatar answered Oct 16 '22 05:10

vinculis