题目描述:
用户表(user)
id (int) | 用户id |
name (varchar) | 用户名 |
gender |
投资表(orders)
id | 订单号 |
user_id | 用户id |
amount(int) | 该笔订单投资额 |
add_time |
1. 求所有投资用户中,投资总额排名前10位的用户,按投资金额倒叙排列,
输出格式为:
用户名,投资金额
张三,800000
李四,600000
......
select b.name, sum(a.account) from orders a
left join user b on a.user_id=b.id
group by a.user_id
order by sum(a.amount) desc
limit 10;
2. 给出投资榜单第一名用户的单笔平均投资额
select user_id, avg(amount)
from orders o
group by o.user_id
order by sum(amount) desc
limit 1;
select avg(amount) from orders
where user_id=
(select user_id from orders group by user_id order by sum(amount) desc limit 1);
note:
1. order by是sql语句,用于对指定的列的结果集进行排序,默认升序
group by是函数,合计函数 (比如 SUM) 常常需要添加 GROUP BY 语句
limit,显示num条检索数据
select accountid,sum(amount) from new_mayi.accountitem group by accountid order by sum(amount) desc limit 10;
limit的其它用法:
select * from Customer LIMIT 10 ;--检索前10行数据,显示1-10条数据
select * from Customer limit 5,10 ;--检索从第6行开始向前加10条数据,共显示id为6,7....15
2. left join关键字会从左表(TABLE_NAME1)那里返回所有的行,即使右表(TABLE_NAME2)中没有匹配的行
SELECT COLUMN_NAME(S) FROM TABLE_NAME1 LEFT JOIN TABLE_NAME2 ON TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUMN_NAME
3. sql语法顺序
SELECT select_list
[ INTO new_table ]
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]