假设我们有一个posts
表,其中包含以下列:id, title, expires_at
。我们想要显示每年每周都没有“过期”的帖子数量。
也许更简单的方法是:“按一年中的几周分组的帖子数量expires_at
日期很好,然后是每周的开始”
例如:
-------------------------------------------------
| Year | Week | posts_not_expired |
------------|-----------|-----------------------|
| 2017 | 01 | 22 |
| 2017 | 02 | 103 |
| 2017 | 03 | 7 |
| ... | ... | ... |
| 2009 | 52 | 63 |
|-----------|-----------|-----------------------|
到目前为止我们有什么:
SELECT
COUNT(id) as posts_not_expired,
YEAR(expires_at) * 100 as Year,
YEARWEEK(expires_at) as Week,
FROM posts
GROUP BY Year, Week
答案 0 :(得分:2)
您可以使用DAYOFWEEK
计算给定周的未过期帖子。 (其中1 =星期日,2 =星期一,... 7 =星期六)
SELECT
YEAR(expires_at) as `Year`,
WEEKOFYEAR(expires_at) as `Week`,
SUM(DAYOFWEEK(expires_at) > 2) as `posts_not_expired`
FROM posts
GROUP BY YEAR(expires_at), WEEKOFYEAR(expires_at)