MySql:查询根据日期添加和分类不同的数据

时间:2015-02-03 03:30:36

标签: mysql sql

我正在尝试提取每月每个唯一身份用户帖子的“帖子”总数,并将其分为2-3个帖子和4个以上的帖子。请参阅下面的示例。无法让它正常工作,请帮忙。

示例DB:

id         Date                    ID             Posts     otherData
-----      ------                  -------        ------    -----------
1          2015-01-24 14:13:50     user1           1        2
2          2015-01-24 14:13:50     user1           3        1
3          2015-01-24 14:13:50     user2           2        4
4          2015-01-24 14:13:50     user3           7        3
5          2015-01-24 14:13:50     user4           0        2
6          2015-02-24 04:13:50     user1           1        3
7          2015-02-24 04:13:50     user1           1        1
8          2015-02-24 04:13:50     user3           1        2

预期结果:

Month     totalUsersThatHavePosted    1 post     2-3Posts          4+Posts
-----     -------------------------   ------     ---------         ------- 
12015     3                           0          1                 2
22015     2                           1          1                 0

我正在尝试这样的查询(但不要认为我很接近):

SELECT CONCAT( MONTH(  `Date` ) , YEAR(  `Date` ) ) AS Month, COUNT(DISTINCT `ID`) 
FROM  `myDB` 
WHERE  `Posts` >0
GROUP BY CONCAT( MONTH(  `Date` ) , YEAR(  `Date` ) ) 

2 个答案:

答案 0 :(得分:0)

这是一个双重聚合查询。首先,由用户和月汇总,以获得计数。然后按月计算最终计数:

select yr, mon, count(*) as TotalUsersPosted,
       sum(cnt in (2, 3)) as posts_2_3,
       sum(cnt >= 4) as posts_4pl 
from (select id, year(date) as yr, month(date) as mon, count(*) as cnt
      from mydb
      group by id, year(date), month(date)
     ) t
group by yr, mon

答案 1 :(得分:0)

我相信这会给你你想要的东西:

SELECT 
Month,COUNT(DISTINCT(user_total)) AS totalUsersThatHavePosted,
SUM((user_total) = 1) as 1_post,
SUM((user_total) in (2, 3)) as 2_3_posts, 
SUM((user_total) > (3)) as 4_plus_posts 
FROM 
(
    SELECT CONCAT(MONTH(Date),
    YEAR(Date)) AS Month,
    ID,
    SUM(Posts) AS user_total 
    FROM myDB 
    WHERE Posts > 0
    GROUP BY Date,ID
) 
AS desired_subset 

GROUP BY Month;