#数据库SQL实战#【Day11】

--------------------------------------------------
学习用,欢迎讨论。
--------------------------------------------------
查看详细题目的方法:
复制以下题目内容;
Ctrl+F查找刚刚复制的题目即可。
--------------------------------------------------
题目49:针对库中的所有表生成select
select 'select count(*) from ' || name || ';'
from sqlite_master where type = 'table'
SQLite的连字符‘||’前面已经介绍过,本题另一个知识点是SQLite的系统表sqlite_master [https://blog.csdn.net/xingfeng0501/article/details/7804378]。
--------------------------------------------------
题目50:将employees表中的所有员工的last_name和first_name通过(')连接起来
select last_name || "'" || first_name as name from employees
根据题意,使用连字符,很容易得到上述语句
--------------------------------------------------
题目51:查找字符串‘10,A,B’
select (length('10,A,B') - length(replace('10,A,B', ',', ''))) as cnt
使用空格换掉逗号(replace),计算两个字符串的长度,差值就是逗号出现的次数。
length()统计字符串的长度,replace(‘字符串’,‘需要替换的子串’,‘用于替换子串的字符串’)
key word: length [http://www.runoob.com/sqlite/sqlite-functions.html], replace
--------------------------------------------------
题目52:获取Employees中的first_name,查询按照first_name最后两个字母,按照升序进行排列
select first_name from employees
order by substr(first_name, -2)
排序使用order by;本题的重点在于“按照first_name最后两个字母排序”。
使用substr()可以获取first_name的最后两个字母。
substr(要截取的字符串, 字符串的起始位置, 截取的字符串的长度),其中字符串的第一个字符的位置为1,位置的取值范围是±(1, 字符串长度);截取的字符串长度取值范围是正整数,若省略,则从起始位置一直截取到字符串末尾;若取值大于剩下的字符串长度,也是截取到字符串末尾为止。
key word: substr
--------------------------------------------------
题目53:按照dept_no进行汇总,属于同一个部门的emp_no按照逗号进行连接,结果给出dept_no以及连接出的结果employees
select dept_no, group_concat(emp_no)
from dept_emp
group by dept_no
本题的重点在于聚合函数group_concat(要连接的字段[, 分隔符(省略时默认为“,”)]),其中连接的顺序是不确定的。group_concat函数需要和group by一起使用。
--------------------------------------------------
题目54:查找排除当前最大、最小salary之后的员工的平均工资avg_salary
select avg(salary) as avr_salary from salaries 
where to_date = '9999-01-01'
and salary not in (select max(salary) from salaries where to_date = '9999-01-01')
and salary not in (select min(salary) from salaries where to_date = '9999-01-01')
对题目正确的解读应该是上面的代码,但是不能通过测试。反而下面的通过了测试:
select avg(salary) as avr_salary from salaries 
where to_date = '9999-01-01'
and salary not in (select max(salary) from salaries)
and salary not in (select min(salary) from salaries)
或者
select avg(salary) as avr_salary from salaries 
where to_date = '9999-01-01'
and salary not in
(
    select max(salary) from salaries
    union
    select min(salary) from salaries
)
--------------------------------------------------
题目55:分页查询employees表,每5行一页,返回第2页的数据
select * from employees limit 5,5
--------------------------------------------------
全部评论

相关推荐

点赞 6 评论
分享
牛客网
牛客企业服务