如何获取子查询组中最近的n个条目?

[英]How to get the most recent n entries in a subquery group?


MySQL 5.5 - in my table logs, how do I sum the values of the n most recent entries per user_id, for all user_ids?

MySQL 5.5 - 在我的表日志中,对于所有user_ids,如何对每个user_id的n个最新条目的值求和?

CREATE  TABLE `logs` (
  `id` INT NOT NULL ,
  `user_id` INT NULL ,
  `value` INT NULL ,
  `date_created` DATETIME NULL ,
  PRIMARY KEY (`id`) );

3 个解决方案

#1


1  

Try this query:

试试这个查询:

SELECT   `user_id`, SUM(`value`)
FROM     logs` as l
WHERE    (SELECT COUNT(*)
          FROM `logs`
          WHERE `user_id` = l.`userid` AND `date_created` > l.`date_created`) < 3
GROUP BY `user_id`

Please note, I have not tested it so it may need a little tweaking.

请注意,我没有测试过,所以可能需要稍微调整一下。

#2


2  

This is a top n per group issue. This page has good information on what you are trying to do:

这是每组问题的前n名。此页面提供了有关您要执行的操作的详细信息:

http://www.artfulsoftware.com/infotree/queries.php#104

#3


-1  

SELECT SUM(*) `TotalSum`
  FROM `logs` log
 INNER JOIN (SELECT MAX(`date_created`) createdDate, id FROM `logs` GROUP BY `user_id`) temp
    ON temp.id=log.id
 GROUP BY log.`user_id`;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/10/11/37c15dc2c7ad6efd4b02ee0e686d0633.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com