选择按一段时间内花费的金额计算的前10个记录?

时间:2012-12-06 14:36:28

标签: mysql

目前,我正在努力检索在一段时间内按金额计算的前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的{​​{1}}购买量最高?

1 个答案:

答案 0 :(得分:2)

你有没有尝试过这样的东西,它会返回所有年份的所有数据:

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

请参阅SQL Fiddle with Demo

但是,如果您希望按年限制,可以添加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