1

目前,我正在努力检索按一段时间内的支出金额计算的前 10 条记录。

MySQL 表:

create table `payment_holder` (
    `user_id` int (11),
    `amount` Decimal (6),
    `date_added` datetime 
); 

演示数据:

insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('4','3.75','2012-03-15 00:41:39');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('5','32.20','2012-03-15 00:42:10');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('6','32.20','2012-03-15 00:42:58');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('7','0.89','2012-03-15 00:48:05');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('8','3.75','2012-03-15 00:50:54');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('4','3.75','2012-03-15 00:41:39');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('5','32.20','2012-03-15 00:42:10');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('6','32.20','2012-03-15 00:42:58');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('7','0.89','2012-03-15 00:48:05');
insert into `payment_holder` (`user_id`, `amount`, `date_added`) values('8','3.75','2012-03-15 00:50:54');

我想从这个例子中检索如下结果:

user_id amount
------------------
6       64.40   
5       64.40   
4       7.5 
8       7.5 
7       1.78

简而言之, 2012 年哪个user_id采购量最高date_added

4

1 回答 1

2

您是否尝试过这样的方法,它将返回所有年份的所有数据:

select user_id, sum(amount) Amount
from payment_holder
group by user_id
order by amount desc
limit 0, 10

请参阅带有演示的 SQL Fiddle

但是,如果您想按年份进行限制,您可以添加一个WHERE子句,将YEAR()函数应用于该date_added字段:

select user_id, sum(amount) Amount
from payment_holder
where year(date_added) = 2012
group by user_id
order by amount desc
limit 0, 10
于 2012-12-06T14:40:25.063 回答