2013-02-19 54 views
1

我有2個MySQL表(用戶和評論) - 我想要做的是獲取一個報告,讓我有多少用戶作出1評論,有多少用戶作出2評論,有多少用戶發表了3條評論,有多少用戶發表了4條評論,按月份和年份分組。mysql查詢(根據他們的活動提取用戶數)

我有這樣的查詢來獲取的,通過年度區分每個用戶提出的意見數量/月

select year(c.datecreated) as comment_year, month(c.datecreated) as comment_month,  
count(c.id) as num_comments 
from tblcomments c 
inner join tbluser u on u.id = c.userid 
where 
c.datecreated <= '2013-02-19' and c.datecreated >= '2012-03-01' 
group by c.userid, year(c.datecreated), month(c.datecreated) 

如何修改這個查詢給我我想要的結果嗎?

回答

2

使用子查詢,以便將結果第二次:

SELECT ym, 
     SUM(c = 1) AS `num_1`, 
     SUM(c = 2) AS `num_2`, 
     SUM(c = 3) AS `num_3`, 
     SUM(c>= 4) AS `num_4+` 
FROM (
    SELECT DATE_FORMAT(datecreated, '%Y-%m') AS ym, COUNT(*) AS c 
    FROM  tblcomments 
    WHERE datecreated BETWEEN '2012-03-01' AND '2013-02-19' 
    GROUP BY ym, userid 
) t 
GROUP BY ym 
+0

太棒了,謝謝! – 2013-02-19 16:46:47

0

下面是做這件事 - 不知道你需要加入對tbluser,但我離開那裏:

SELECT comment_year, comment_month, 
    COUNT(userId) userCnt, 
    Num_Comments 
FROM (
    select 
    year(c.datecreated) as comment_year, 
    month(c.datecreated) as comment_month,  
    c.userid, 
    CASE WHEN count(c.id) >= 4 THEN '4+' ELSE CAST(COUNT(c.id) as varchar) END as num_comments 
    from tblcomments c 
    inner join tbluser u on u.id = c.userid 
    where 
    c.datecreated <= '2013-02-19' and c.datecreated >= '2012-03-01' 
    group by c.userid, year(c.datecreated), month(c.datecreated) 
) t 
GROUP BY comment_year, comment_month, Num_Comments; 

還有一些樣品小提琴:http://sqlfiddle.com/#!3/5fb5c/5

相關問題