mysql分组求和,并对和排序、取top n

面试时遇到的一个问题,当时我都把那个sql在纸上写出来了,面试官也没看我写得是什么,我自己也不敢确定,然后支支吾吾对面试官说没有写出来。现在回想起来,多么简单的一个sql,愧对我那些年写过的代码。

还有就是在面试时写算法或sql语句时,按着自己的想法写出来,不管自己确不确定,先给面试官看,没准面试官会给你屡思路,自己也会从中学习。

来看问题:

create table tb_user_finance (
  id bigint primary key auto_increment,
  uid bigint not null default 0 comment '用户id',
  money decimal(10, 2) not null default 0.00 comment '资金流水',
  type tinyint not null default 0 comment '1: 转账, 10: 提现, 20: 充值',
  created_at timestamp not null default current_timestamp,
  updated_at timestamp not null default current_timestamp on update current_timestamp,
  key ix_uid (uid)
) engine = innodb default charset=utf8 comment '用户资金流水表';

insert into tb_user_finance (uid, money, type) values(10, 20, 1);
insert into tb_user_finance (uid, money, type) values(10, 20, 1);
insert into tb_user_finance (uid, money, type) values(10, 20, 1);
insert into tb_user_finance (uid, money, type) values(10, 200, 1);

insert into tb_user_finance (uid, money, type) values(20, 10, 10);
insert into tb_user_finance (uid, money, type) values(30, 20, 20);
insert into tb_user_finance (uid, money, type) values(30, 10, 20);

insert into tb_user_finance (uid, money, type) values(31, 10, 20);
insert into tb_user_finance (uid, money, type) values(32, 20, 20);
insert into tb_user_finance (uid, money, type) values(33, 45, 20);
insert into tb_user_finance (uid, money, type) values(34, 100, 20);
insert into tb_user_finance (uid, money, type) values(35, 1000, 20);
insert into tb_user_finance (uid, money, type) values(36, 1090, 20);

有一个用户资金流水表(如上的sql代码),找出流水金额最多的前10个用户:

select uid, sum(money) as total from tb_user_finance group by uid order by total desc limit 10;

sql根本不难,多注意细节的积累吧!

参考:MySQL获取分组后的TOP 1和TOP N记录

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值