从表格宽度日期字段获取每周分数

时间:2014-11-28 17:29:06

标签: mysql sql

我有这张桌子:

    -------------------------------------------
    |id      |duration  |date           |uid  |
    -------------------------------------------
    |1       |20        |1392479414     |1    |
    |2       |60        |1392561057     |1    |
    |3       |50        |1392598128     |2    |
    |...                                      |
    |...                                      |
    -------------------------------------------

有没有一种简单的方法可以从中获得每周累积分数,而无需手动计算周开始/结束日期,并查询每个日期以获得这些日期之间的分数?

所以我得到了:

    ---------------
    |sum_duration |
    ---------------
    |2450         |
    |12350        |
    |400          |
    |...          |
    |...          |
    ---------------

非常感谢。

2 个答案:

答案 0 :(得分:1)

呀。 GROUP BY周数。

获取所有结果

SELECT SUM(`duration`) AS sum_duration, DATE_FORMAT(FROM_UNIXTIME(`date`), '%U') as week_no
FROM `foo`
GROUP BY DATE_FORMAT(FROM_UNIXTIME(`date`), '%U')

根据您的数据集,我们会得到;

+--------------+---------+
| sum_duration | week_no |
+--------------+---------+
|           20 | 06      |
|          110 | 07      |
+--------------+---------+
2 rows in set

获得某一周

如果您想获得特定的一周,只需将HAVING week_no = '07'添加到最后。 (将07替换为您的周数。例如;

SELECT
    SUM(`duration`) AS sum_duration,
    DATE_FORMAT(FROM_UNIXTIME(`date`), '%U') AS week_no
FROM
    `foo`
GROUP BY
    DATE_FORMAT(FROM_UNIXTIME(`date`), '%U')
HAVING
    week_no = '07';

我们会得到以下结果;

+--------------+---------+
| sum_duration | week_no |
+--------------+---------+
|          110 | 07      |
+--------------+---------+
1 row in set

答案 1 :(得分:0)

如果您使用MySQL,则可以使用WEEKYEARWEEK功能。我认为YEARWEEK更好。这是MySQL文档http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week

SELECT SUM(duration) FROM table_name GROUP BY YEARWEEK(date)