MySQL 5.5 - 在我的表日志中,如何为所有user_id对每个user_id的n个最新条目的值求和?
CREATE TABLE `logs` (
`id` INT NOT NULL ,
`user_id` INT NULL ,
`value` INT NULL ,
`date_created` DATETIME NULL ,
PRIMARY KEY (`id`) );
答案 0 :(得分:2)
这是每组问题的前n名。此页面提供了有关您要执行的操作的详细信息:
答案 1 :(得分:1)
尝试此查询:
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`
请注意,我没有测试过,所以可能需要稍微调整一下。
答案 2 :(得分:-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`;