我有一张表如下
CREATE TABLE messages (
id int(10) UNSIGNED AUTO_INCREMENT NOT NULL,
messagetext text NOT NULL,
created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY(id)
)
我想要做的是获得两周的数据,当前周和前一周,按天排序。例如,在星期日,星期一,星期二,星期三......本周和上周创建了多少条消息。
我的查询如下
SELECT
COUNT(id) AS 'Count'
FROM
'messages'
WHERE
(WEEK(created_at) = WEEK(NOW()))
GROUP BY
WEEKDAY(created_at)
ORDER BY
week(created_at) ASC,
weekday(created_at) ASC
但我不知道如何整理它。例如,上面的查询将列出我今天或昨天获得了多少,但这不是我想要的。我想要的是明天和明智的计算日。
如果我对自己面临的情况有足够的清楚,请告诉我。
更新 有关更多信息,请参阅下面的Juan的问题
如果当前天数少于14天,那么在这种情况下,脚本应该返回上周的天数,而不是前一周的前一天。以下是胡安的解释(想象今天是星期五。如果你算上14天回来,你星期一星期五到星期五。星期一星期一到星期日...并且上周五星期五到星期日。并且不确定这是否是你的结果想要)
问候
加甘
答案 0 :(得分:0)
我要发一个大猜测。但你尝试过这样的事吗?
SELECT
week(created_at) week_id,
weekday(created_at) weekday_id,
COUNT(id) AS 'Count'
FROM
'messages'
WHERE
week_id = WEEK( NOW() )
OR week_id = WEEK( DATE_SUB(NOW(), INTERVAL 7 DAY) )
GROUP BY
week_id, weekday_id
ORDER BY
week_id, weekday_id
答案 1 :(得分:0)
使用条件SUM
SELECT week(created_at) week_id,
SUM( IF(weekday(created_at) = 0, 1, 0) ) as monday,
SUM( IF(weekday(created_at) = 1, 1, 0) ) as tuesday,
SUM( IF(weekday(created_at) = 2, 1, 0) ) as wednesday,
SUM( IF(weekday(created_at) = 3, 1, 0) ) as thursday,
SUM( IF(weekday(created_at) = 4, 1, 0) ) as friday,
SUM( IF(weekday(created_at) = 5, 1, 0) ) as saturday,
SUM( IF(weekday(created_at) = 6, 1, 0) ) as sunday
FROM 'messages'
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 14 DAY)
AND ( week_id = WEEK( NOW() )
OR week_id = WEEK( DATE_SUB(NOW(), INTERVAL 7 DAY)
)
GROUP BY
week_id
ORDER BY
week_id