Now I understand that this has been asked several times before, but I have tried to apply different existing solutions to my specific problems for quite a while without success. So I turn here in hope of some guidance.
I have a table called tblanswers, which contains answers linked to different questions in another table. What I want is to get the count for each answer for a specific question ID, but limit it to the n first answers each month.
Sample data from tblanswers:
id  qid answer  timestamp
72  162 2       1366027324
71  161 4       1343599200
70  162 2       1366014201
69  161 4       1366011700
68  162 2       1366006729
67  161 3       1366010948
66  162 2       1365951084
This is the query I have so far:
SELECT *, COUNT(*) c FROM(
    SELECT answer, timestamp, YEAR(FROM_UNIXTIME(timestamp)) yr, MONTH(FROM_UNIXTIME(timestamp)) mo FROM tblanswers
        WHERE qid = 161
            ORDER BY timestamp ASC
) q GROUP BY YEAR(FROM_UNIXTIME(timestamp)), MONTH(FROM_UNIXTIME(timestamp)), answer
That would give me something like this: (the dates and numbers in sample data is not accurate)
answer  yr      mo  c
1       2013    5   5
2       2013    5   3
3       2013    5   2
1       2013    6   5
2       2013    6   15
3       2013    6   7
Let's say I only want to see the first three answers in a month, then count could never be more than 3. How can I limit each month?
The final data should be a sum of each answer, like this:
answer num_answers
1      2
2      3
3      3
I think one of these solutions could work, but not how: http://code.openark.org/blog/mysql/sql-selecting-top-n-records-per-group http://code.openark.org/blog/mysql/sql-selecting-top-n-records-per-group-another-solution
Any help is appreciated. Thanks!
 
     
     
     
    