3

我有一个名为“results”的表,其中包含很多行和一个名为“timestamp”的列。

我想对每个月的行数进行分组。但是对于其中的每一个,我还想考虑前几个月的行。

所以如果我有

Jun/13
Jun/13
Jun/13
Jul/13
Jul/13
Jul/13
Jul/13
Jul/13
Aug/13
Aug/13
Aug/13
Aug/13
Aug/13
Aug/13
Aug/13

结果将是

3  Jun/13
8  Jul/13
15 Aug/13

这是我现在所拥有的,但它不考虑前几个月。

SELECT DATE_FORMAT(FROM_UNIXTIME(timestamp), '%e %b %Y'), COUNT(1) FROM results
GROUP BY DATE_FORMAT(FROM_UNIXTIME(timestamp), '%e %b %Y');
4

3 回答 3

3

我得到了这个工作:

SELECT month, count, @total:=@total+count AS total
FROM (SELECT @total:=0) t STRAIGHT_JOIN
  (SELECT DATE_FORMAT(FROM_UNIXTIME(timestamp), '%e %b %Y') AS month, COUNT(*) AS count
  FROM results GROUP BY EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(timestamp))) AS m;

+------------+-------+-------+
| month      | count | total |
+------------+-------+-------+
| 1 Jun 2013 |     3 |     3 |
| 1 Jul 2013 |     5 |     8 |
| 1 Aug 2013 |     7 |    15 |
+------------+-------+-------+
于 2013-06-05T17:38:12.203 回答
1

以下解决方案应该可行...

SELECT COUNT(1), DATE_FORMAT(timestamp, '%b/%y') FROM results GROUP BY YEAR(timestamp), MONTH(timestamp);

祝你好运

Talki

于 2013-06-05T17:31:58.570 回答
0

如果我理解正确,这应该有效;

SELECT COUNT(*) num, SUBSTR(ts, 1, 7) month
FROM results
JOIN (SELECT MAX(timestamp) ts FROM results
      GROUP BY YEAR(timestamp),Month(timestamp)) mm
  ON results.timestamp <= mm.ts
GROUP BY SUBSTR(ts, 1, 7);

一个用于测试的 SQLfiddle

于 2013-06-05T17:45:27.750 回答