我有下面的查询来获取行数并按周分组。它很棒。
SELECT
WEEKOFYEAR(searched_on) AS weekno,
COUNT(*) AS num_search,
SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,
FROM table
GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY)) ORDER BY weekno ASC
如何修改此项,以便在不使用ORDER BY weekno DESC LIMIT 5
的情况下仅选择最后5个结果,以免改变数据的排列方式。感谢
答案 0 :(得分:6)
您可以添加ORDER BY weekno DESC LIMIT 5
并将查询推送到子查询中,然后让外部查询重新排序:
SELECT * FROM (
SELECT
WEEKOFYEAR(searched_on) AS weekno,
COUNT(*) AS num_search,
SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,
FROM table
GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY))
ORDER BY weekno DESC LIMIT 5
) inner
ORDER BY weekno
答案 1 :(得分:3)
只需使用mysql中使用的limit
。
在代码limit 5
之后添加ORDER BY weekno ASC
。意味着在查询结束时添加它。
这是the tutorial。
使用以下查询:
SELECT
WEEKOFYEAR(searched_on) AS weekno,
COUNT(*) AS num_search,
SUBDATE(searched_on, INTERVAL WEEKDAY(searched_on) DAY), INTERVAL + 0 DAY AS date_of_week,
FROM table
GROUP BY WEEK(DATE_SUB(searched_on, INTERVAL 1 DAY)) ORDER BY weekno ASC
LIMIT 5 OFFSET (num_search-5) //add this line