MySQL查询返回每个月之前创建的所有行

时间:2016-11-15 15:45:59

标签: mysql date count

我有一个用户表:

|id |created_at|
|---|----------|
|1  |2016-11-15|
|2  |2016-08-30|
|3  |2016-06-23|
|4  |2015-12-03|

我想运行一个返回每个月的查询以及在该月之前创建的行数。 我现在的查询是:

SELECT YEAR(created_at) AS `year`, MONTH(created_at) AS `month`, COUNT(*) AS `count`
FROM users
GROUP BY `year`, `month`
ORDER BY `year` DESC, `month` DESC

返回下表:

|year|month|count|
|----|-----|-----|
|2016|11   |1    |
|2016|8    |1    |
|2016|6    |1    |
|2015|12   |1    |

我想要的表格如下:

|year|month|count|
|----|-----|-----|
|2016|11   |4    |
|2016|8    |3    |
|2016|6    |2    |
|2015|12   |1    |

甚至更好:

|year|month|count|
|----|-----|-----|
|2016|11   |4    |
|2016|10   |3    |
|2016|9    |3    |
|2016|8    |3    |
|2016|7    |2    |
|2016|6    |2    |
|2016|5    |1    |
|2016|4    |1    |
|2016|3    |1    |
|2016|2    |1    |
|2016|1    |1    |
|2015|12   |1    |
|2015|11   |0    |

2 个答案:

答案 0 :(得分:1)

尝试测试一下。

SELECT YEAR(Created) as Year, MONTH(Created) as Month,
      count(*) AS num_daily_interactions,
       (
          SELECT 
             COUNT(*)
          FROM users l2
          WHERE DATE(l2.created_at) <= l1.created_at
       ) as total_interactions_per_day

    FROM `users ` as l1

    GROUP BY YEAR(created_at), MONTH(created_at)
    ORDER BY YEAR(created_at) DESC, MONTH(created_at) DESC;

答案 1 :(得分:0)

SET @tot=0;
SELECT max(rank) AS `cm` ,ym,count(*) AS `ct` 
FROM (
SELECT concat_ws('',YEAR(created_at) ,LPAD( MONTH(created_at),2,'0') ) AS `ym` ,@tot:=@tot + 1 AS `rank` FROM users
ORDER BY ym DESC) as a
GROUP BY ym