kevi kevi
kevi kevi

Reputation: 167

MySql query - Grouping by date ranges?

I'm trying to write a query that will return data grouped by date ranges and am wondering if there's a way to do it in one query (including the calculation), or if I need to write three separate ones? The dates in my table are stored as unix timestamps.

For example, my records look like this:

id  type    timestamp
312 87  1299218991
313 87  1299299232
314 90  1299337639
315 87  1299344130
316 87  1299348977
497 343 1304280210
498 343 1304280392
499 343 1304280725
500 343 1304280856
501 343 1304281015
502 343 1304281200
503 343 1304281287
504 343 1304281447
505 343 1304281874
566 90  1305222137
567 343 1305250276
568 343 1305387869
569 343 1305401114
570 343 1305405062
571 343 1305415659
573 343 1305421418
574 343 1305431457
575 90  1305431756
576 343 1305432456
577 259 1305441833
578 259 1305442234
580 343 1305456152
581 343 1305467261
582 343 1305483902

I'm trying to write a query that will find all records with a "created" date between:

  1. 2011-05-01 and 2011-06-01 (Month)
  2. 2011-03-01 and 2011-06-01 (Quarter)
  3. 2010-05-01 AND 2011-06-01 (Year)

I tried the following (in this case, I hardcoded the unix value for just the month to see if I could get it to work... ):

SELECT COUNT(id) AS idCount,
MIN(FROM_UNIXTIME(timestamp)) AS fromValue, 
MAX(FROM_UNIXTIME(timestamp)) AS toValue
FROM uc_items 
WHERE ADDDATE(FROM_UNIXTIME(timestamp), INTERVAL 1 MONTH) 
      >= FROM_UNIXTIME(1304233200)

But, it doesn't seem to work because the fromValue is: 2011-04-02 21:12:56 and the toValue is 2011-10-25 06:20:14, which, obviously, isn't a date between 5/1/2011 and 6/1/2011.

Upvotes: 0

Views: 320

Answers (1)

Eric Petroelje
Eric Petroelje

Reputation: 60498

This aught to work:

SELECT COUNT(id) AS idCount,
   FROM_UNIXTIME(MIN(timestamp)) AS fromValue, 
   FROM_UNIXTIME(MAX(timestamp)) AS toValue
FROM uc_items
WHERE timestamp BETWEEN UNIX_TIMESTAMP('2011-05-01') AND UNIX_TIMESTAMP('2011-06-01 23:59:59')

Also, as a performance tip - avoid applying functions to columns in your tables in a WHERE clause (e.g you have WHERE ADDDATE(FROM_UNIXTIME(timestamp))). Doing that will prevent MySQL from using any indexes on the timestamp column.

Upvotes: 2

Related Questions