使用MySQL以不同的顺序和数量从同一个表中提取信息

时间:2012-06-27 19:01:58

标签: mysql count group-by nested running-total

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

+--------+------------+
| name   | date       |
+--------+------------+
| 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 
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);

输出;

+------------+-------+-----------+
| date       | count | run_total |
+------------+-------+-----------+
| 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
FROM
(SELECT D1.date, Count(D1.person_id) as c, @s := 0
FROM table D1
GROUP BY month(D1.date)
ORDER BY D1.date desc limit 4) as T1)
ORDER BY date;

但我没有得到理想的结果;

+------------+-------+-----------+
| date       | count | run_total |
+------------+-------+-----------+
| 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 |
+------------+-------+-----------+

2 个答案:

答案 0 :(得分: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条记录,然后按日期重新排序 总数保持不变。

答案 1 :(得分: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;