开发者

Create a report show specific stats for each day between a start and end date

I have a table with that contains information that I would like to show stats for each day between a particular range of dates. The table consists of the following:

CREATE TABLE IF NOT EXISTS `questions` (
  `qid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `question_created_date` datetime NOT NULL,
  `question_response_date` datetime NOT NULL,
)

I am able to use the following query to displays the amount of questions created on each day between $start_date and $end_date.

SELECT COUNT(*) as q_count, DATE(question_created_date) as date FROM questions where question_created_date between "$start_date" and "$end_date" GROUP BY date ORDER BY date asc

I would also like for it to list the amount of topics that were responded to on the same days. For exmaple if on 7/5/11 there were开发者_如何学Go 10 new questions and 5 questions responded to and on 7/6/11 there were 5 new questions and 11 questions responded to, I want to be able to show:

Date|New|Responded

7/5/11 10 05
7/6/11 05 11

Can this be done via mysql?

I know I can perform the query listed above and then for each day perform another query to get the amount of questions responded to for that day, but I was wondering if there was an easier and more efficient way to do this in one query.

Thanks in advance.


The two dates aren't related to each other, except that logically, the response date could only ever be greater than the created date. Grouping on one date will destroy any information you could extract from the other date, so in other words - you'll need two queries.

The fields returned would be the same - a count and a date field, so you could issue this is as a single query call, but it'd have to be done as a union query:

SELECT 'created' as src, count(*) as cnt, DATE(question_created_date) as created ...

UNION

SELECT 'answered' as src, count(*) as cnt, etc...

The virtual 'src' column will tell you which internal query produced the result, and the union syntax lets you issue this all as a single query. But within MySQL, it'd still be treated as two completely separate queries, whose results just happen be returned all at once.


You could do something like this using UNION. MySQL possibly has a built in operator that is more efficient, but this will work too:

select main.date, max(qcd), max(qrd) from 
(SELECT DATE(question_created_date) as date, count(*) as qcd, 0 as qrd FROM questions  
    where question_created_date between "$startdate" and "$enddate" GROUP BY date
union
SELECT DATE(question_response_date) as date, 0, count(*) as qrd FROM questions 
    where question_response_date between "$startdate" and "$enddate" GROUP BY date) 
main group by main.date order by main.date asc;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜