赞
踩
问题: table1(id:自增id,money:费用)问题:按id顺序累加money,取出累计值与1000相差最小差值的id。
建表语句:
- create table `table1` (
- `id` int default null auto_increment primary key,
- `money` int default null
- ) engine=innodb default charset=utf8;
- insert into `table1` values (1,100),(1,300),(1,500),(1,700),(2,200),(2,400),(2,500),(2,700),(2,900),(3,100),(3,400),(3,700);
内容简单,本来不值当记一下的,但是表都建好了,又不想白写,所以就记录一下!
SQL语句:
- select id, abs(sum(money) - 1000) as diff
- from table1
- group by id
- order by diff
- limit 1
运行结果:
题目来自逆流大神的专栏:
逆流:sql 面试题(难题汇总)zhuanlan.zhihu.comCopyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。