MYSQL如何计算日期范围内列的总和

时间:2014-03-09 18:08:33

标签: mysql sql

表格如下:

date       name    count
2013-1-1   Jack     20
2014-3-8   Jack     3
2014-3-1   Tom      1
2014-3-1   Jack     7
2014-2-28  Mary     4
2014-2-28  Tom      5

我想写一个查询来输出最近30天内总人数的人

eg. 
    Jack 10
    Tom  6
    Mary 4

执行此操作的最简单的SQL是什么?

2 个答案:

答案 0 :(得分:2)

您可以使用:

SELECT name, SUM(count) FROM table_name WHERE date >= ( CURDATE() - INTERVAL 30 DAY ) GROUP BY name; 

答案 1 :(得分:0)

更新:按suggested

查询MatBailie
mysql> SELECT
    ->    name, 
    ->    SUM(count) as total_count
    -> FROM table_name
    -> WHERE `date` >= DATE_SUB(NOW(), INTERVAL 30 day) AND `date` <= NOW()
    -> GROUP BY name    
    -> ;
+------+-------------+
| name | total_count |
+------+-------------+
| Jack |          10 |
| Mary |           4 |
| Tom  |           6 |
+------+-------------+
3 rows in set (0.02 sec)

旧回答:

尝试:

SELECT
   name, 
   SUM(count) as total_count
FROM table_name
WHERE ABS(DATEDIFF(`date` , now())) < 30
GROUP BY name

它正在运作:

mysql> create table table_name (`date` datetime, name char(20), count int);
Query OK, 0 rows affected (0.21 sec)

mysql> insert into table_name values
    -> ('2013-1-1',   'Jack',     20),
    -> ('2014-3-8',   'Jack',     3),
    -> ('2014-3-1',   'Tom',      1),
    -> ('2014-3-1',   'Jack',     7),
    -> ('2014-2-28',  'Mary',     4),
    -> ('2014-2-28',  'Tom',      5);
Query OK, 6 rows affected (0.12 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> SELECT
    ->    name, 
    ->    SUM(count) as total_count
    -> FROM table_name
    -> WHERE ABS(DATEDIFF(`date` , now())) < 30
    -> GROUP BY name;
+------+-------------+
| name | total_count |
+------+-------------+
| Jack |          10 |
| Mary |           4 |
| Tom  |           6 |
+------+-------------+
3 rows in set (0.00 sec)

编辑:根据评论:

  

如果我想获得杰克和汤姆最高分的前2名。怎么做?。

使用ORDER BY DESCLIMIT,检查以下查询结果。

mysql> SELECT
    ->    name, 
    ->    SUM(count) as total_count
    -> FROM table_name
    -> WHERE `date` > DATE_SUB(NOW(), INTERVAL 30 day) and `date` < NOW()
    -> GROUP BY name
    -> ORDER BY total_count DESC
    -> LIMIT 2;
+------+-------------+
| name | total_count |
+------+-------------+
| Jack |          10 |
| Tom  |           6 |
+------+-------------+
2 rows in set (0.03 sec)