我在这个结构中有一个表:
editor_id
rev_user
rev_year
rev_month
rev_page
edit_count
这是sqlFiddle:http://sqlfiddle.com/#!2/8cbb1/1
我需要在2011年3月期间展示5个最活跃的编辑器 - 例如,对于每个rev_user - 将每个rev_month的所有edit_count和所有rev_pages的rev_year相加。
有任何建议吗?
更新 - 更新了演示数据
答案 0 :(得分:1)
你应该能够这样做:
SUM
和GROUP BY
选择总计,按rev_year
和rev_month
SUM
降序排列以下是:
SELECT * FROM (
SELECT rev_user, SUM(edit_count) AS total_edits
FROM edit_count_user_date
rev_year='2006' AND rev_month='09'
GROUP BY rev_user
) x
ORDER BY total_edits DESC
LIMIT 5
答案 1 :(得分:0)
当然这很简单:
SELECT rev_user, SUM(edit_count) as TotalEdits
FROM edit_count_user_date
WHERE rev_month = 'March' and rev_year = '2014'
GROUP BY rev_user
ORDER BY TotalEdits DESC
LIMIT 5;
我是否还建议使用更合适的DATE
类型进行年度和月份存储?
修改,新信息
以下内容将返回“最高”MonthTotal
编辑器的给定月份的所有修改,然后按rev_page
重新分组总计。
SELECT e.rev_user, e.rev_page, SUM(e.edit_count) as TotalEdits
FROM edit_count_user_date e
INNER JOIN
(
SELECT rev_user, rev_year, rev_month, SUM(edit_count) AS MonthTotal
FROM edit_count_user_date
WHERE rev_month = '09' and rev_year = '2010'
GROUP BY rev_user, rev_year, rev_month
ORDER BY MonthTotal DESC
LIMIT 1
) as x
ON e.rev_user = x.rev_user AND e.rev_month = x.rev_month AND e.rev_year = x.rev_year
GROUP BY e.rev_user, e.rev_page;
SqlFiddle here - 我调整了数据以使其更有趣。
但是,如果你需要在几个月内同时执行此操作,那么由于MySql缺少partition by
/ analytical windowing functions,这将更加困难。