欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

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;  #按总钱最多排序
select uid, count(money) as cou from tb_user_finance group by uid order by total desc limit 10;  #按次数最多排序

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


来自 http://www.voidcn.com/article/p-azqikufw-brs.html


普通分类: