我有这张桌子:
-------------------------------------------
|id |duration |date |uid |
-------------------------------------------
|1 |20 |1392479414 |1 |
|2 |60 |1392561057 |1 |
|3 |50 |1392598128 |2 |
|... |
|... |
-------------------------------------------
有没有一种简单的方法可以从中获得每周累积分数,而无需手动计算周开始/结束日期,并查询每个日期以获得这些日期之间的分数?
所以我得到了:
---------------
|sum_duration |
---------------
|2450 |
|12350 |
|400 |
|... |
|... |
---------------
非常感谢。
答案 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,则可以使用WEEK
或YEARWEEK
功能。我认为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)