1

第一次发帖。例如,假设我有一个包含 12 个条目的表;

+--------+------------+
| 姓名 | 日期 |
+--------+------------+
| P1 | 2011-12-01 |
| P2 | 2012-01-01 |
| P3 | 2012-02-01 |
| P4 | 2012-02-01 |
| P5 | 2012-02-01 |
| P6 | 2012-05-01 |
| P7 | 2012-04-01 |
| P8 | 2012-05-01 |
| P9 | 2012-05-01 |
| P10 | 2012-06-01 |
| P11 | 2012-06-01 |
| P12 | 2012-03-01 |
+--------+------------+

我已经日期对表中的信息进行了分组,记录了所有 id 的计数(未显示)并创建了一个运行总计。我已经这样做了;

(SELECT date, c as count, (@s := @s + c) as run_total
从
(SELECT D1.date, Count(D1.person_id) as c, @s := 0
从表 D1
按月分组(D1.日期)
ORDER BY D1.date) 作为 T1);

输出;

+------------+-------+------------+
| 日期 | 计数 | 运行总计 |
+------------+-------+------------+
| 2011-12-20 | 1 | 1 |
| 2012-01-31 | 1 | 2 |
| 2012-02-20 | 3 | 5 |
| 2012-03-05 | 1 | 6 |
| 2012-04-20 | 1 | 7 |
| 2012-05-20 | 3 | 10 |
| 2012-06-01 | 2 | 12 |
+------------+-------+------------+

目前很好。这是我松开它的地方。我怎样才能提取最近的 4 个条目并得到像这样的东西???其中日期保持升序,更重要的是 run_total 保持不变;

-----我想要达到的目标-----

----------------------------------
| 2012-03-05 | 1 | 6 |
| 2012-04-20 | 1 | 7 |
| 2012-05-20 | 3 | 10 |
| 2012-06-01 | 2 | 12 |
+------------+-------+------------+

-------------------------------------

为了解决这个问题,我创造了这个;

(SELECT date, c as count, (@s := @s + c) as run_total
从
(SELECT D1.date, Count(D1.person_id) as c, @s := 0
从表 D1
按月分组(D1.日期)
ORDER BY D1.date desc 限制 4) 作为 T1)
按日期订购;

但是我没有得到想要的结果;

+------------+-------+------------+
| 日期 | 计数 | 运行总计 |
+------------+-------+------------+
| 2012-03-05 | 1 | 1 |
| 2012-04-20 | 1 | 2 |
| 2012-05-20 | 3 | 5 |
| 2012-06-01 | 2 | 7 |
+------------+-------+------------+

日期是有序的,但 run_totals 都搞砸了。1 应该是 6、2 -> 7、5 -> 10 和 7 -> 12,如前所示。

同样,我想要实现的是;

----------------------------------
| 2012-03-05 | 1 | 6 |
| 2012-04-20 | 1 | 7 |
| 2012-05-20 | 3 | 10 |
| 2012-06-01 | 2 | 12 |
+------------+-------+------------+
4

2 回答 2

1
SELECT * FROM
(SELECT *
FROM (SELECT date, count, (@s := @s + c) as run_total 
FROM
(SELECT D1.date, Count(D1.person_id) as c, @s := 0
FROM table D1
GROUP BY month(D1.date)
ORDER BY D1.date) as T1) tmp
ORDER BY `date` DESC
LIMIT 4) tmp2
ORDER BY `date` ASC

它获取您查询的 4 条最新记录,然后按日期对它们重新排序。
总数保持不变。

于 2012-06-27T19:06:43.173 回答
0
(SELECT date, c as count, (@s := @s + c) as run_total 
FROM
(SELECT D1.date, Count(D1.person_id) as c, @s := 0
FROM table D1
GROUP BY month(D1.date)
ORDER BY D1.date ASC) as T1) LIMIT 4;
于 2012-06-27T19:07:17.387 回答