2

i have this scheme:

+-------+
|posts: |
+----+--+--------+--------------------+
| ID |   title   |      timestamp     |
+----+-----------+--------------------+
|  1 |    t1     |2011-04-05 17:54:55 |
+----+-----------+--------------------+ 
|  2 |    t2     |2011-04-06 09:10:11 |
+----+-----------+--------------------+ 
|  3 |    t3     |2011-04-07 02:07:22 |
+----+-----------+--------------------+ 

How i can get the total of posts for last 7 days grouped like this:

monday: 3
Tuesday: 9
Wednesday: 2
greenbandit
  • 2,267
  • 5
  • 30
  • 44

3 Answers3

3

Well,

you would have to select the date, make a count(*) and group by date.

SELECT date_format(TIMESTAMP, '%d %m')
       , COUNT(*)
FROM posts
WHERE TIMESTAMP BETWEEN FROMDATE AND TODATE
GROUP BY date_format(TIMESTAMP, '%d %m')

further help and explanation: MySQL Manual for DATE_FORMAT

EDIT:

Weekday can also be achieved with this function by using %W.

DKSan
  • 4,187
  • 3
  • 25
  • 35
3

MySQL specific solutions:

SELECT WEEKDAY(timestamp_field) AS wd, count(*) FROM your_table GROUP BY wd;

or

SELECT count(*) FROM your_table GROUP BY WEEKDAY(timestamp_field);
Denis Otkidach
  • 32,032
  • 8
  • 79
  • 100
2
SELECT WEEKDAY(timestamp), count(*)
FROM POSTS as p1
WHERE DATE_SUB(NOW(), INTERVAL 7 DAY) < timestamp
GROUP BY YEAR(timestamp), MONTH(timestamp), DAY(timestamp)
ORDER BY YEAR(timestamp) desc, MONTH(timestamp) desc, DAY(timestamp) desc

Check out the date and time functions in MySQL.

Chris Frederick
  • 5,482
  • 3
  • 36
  • 44
Capitaine
  • 1,923
  • 6
  • 27
  • 46
  • but if some day has 0 entries, that day is lost. – greenbandit Apr 06 '11 at 21:54
  • 1
    added weekday(timestamp) for clarification. if 0 entries, rows would not be shown from one single table. unless there are other tables consisting every day information, then we can do the left join to ensure all rows are there, but it causes relatively high overhead. instead, I suggest you may do the simple checking on this in your server side. – Capitaine Apr 07 '11 at 07:49