SQL在列中选择聚合值

时间:2014-05-25 16:00:38

标签: mysql sql

我在这个结构中有一个表:

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相加。

有任何建议吗?

更新 - 更新了演示数据

2 个答案:

答案 0 :(得分:1)

你应该能够这样做:

  • 使用SUMGROUP BY选择总计,按rev_yearrev_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

Demo on sqlfiddle.

答案 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;

SqlFiddle here

我是否还建议使用更合适的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,这将更加困难。