简体   繁体   中英

Mysql query to find number of occurrences of a value in a given date range

I have a table with 7,000,000 rows and two columns: a name and a timestamp. The data in it look something like this:

NAME  - TIMESTAMP
Arnie - 2012-05-15 09:31:21
Arnie - 2012-05-15 10:31:21
Jethro - 2012-05-15 12:31:21
Regina - 2012-05-15 12:31:21
Beatriz - 2012-05-16 0:31:21
Jethro - 2012-05-15 08:31:21
Jethro - 2012-06-15 08:31:21
Jethro - 2012-06-16 08:31:21
Archie - 2012-06-16 09:31:21
Jethro - 2012-06-17 08:31:21

For every month since January 2012 I want to know how many times each name appeared that month so for the sample above I would want:

June 2012

Arnie - 2
Jethro - 2
Regina - 1
Beatriz - 1

July 2012

Jethro - 3
Archie - 1

What is the best way to do this? Also, Is there a way to run this as one query that groups the timestamps by month or should I just make a loop in PHP and run a separate query for each month?

I know this isn't super difficult and is surely covered in the docs but I'm confused as to the terms to search for.

you can use GROUP BY and get the count , you can use MONTHNAME

SELECT Name, MONTHNAME(TIMESTAMP) AS Month, COUNT(*) AS count
FROM Table1
GROUP BY NAME, MONTHNAME(TIMESTAMP)

Try this:

select date_format(timestamp, '%Y %M') as yyyymm, name, count(*)
from table t
group by date_format(timestamp, '%Y %M'), name
order by min(timestamp), name;

Note that the output format is slightly different from what you propose. This adds the year/month to each row as a separate column. This format is more consistent with relational result sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM