SQL245 查找字符串中逗号出现的次数
- length(s)函数: s是字符串, 返回的是所求的字符串s的长度。 replace(a,b,c):
在字符串a中,将a中出现的b,替换成c。再把这个替换之后的串的结果返回。
select
id,
length(string)-length(replace(string,",","")) as cnt
from strings
SQL246 获取emplovees中的frst name
- substring(X,Y) 函数:
其中X是要截取的字符串,Y是字符串的起始位置(注意第一个字符的位置为1,而不为0),当Y等于length(X)时,则截取最后一个字符;当Y等于负整数-n时,则从倒数第n个字符处截取。 - substring(X,Y,Z) 函数:
Z是要截取字符串的长度,取值范围是正整数,若Z省略,则从Y处一直截取到字符串末尾;若Z大于剩下的字符串长度,也是截取到字符串末尾为止。
select first_name
from employees
order by substring(first_name,-2)
SQL247 按照dept no进行汇总
- group_concat(),功能是将要连接的字段按照排序字段的顺序用分隔符连起来显示,默认分隔符是”,”,可用 separator ‘分隔符’ 修改分隔符.
select
dept_no,
group_concat(emp_no) as employees
from dept_emp
group by dept_no
SQL248 平均工资
- 在where中直接将最高薪资和最低薪资去掉
select
avg(a.salary) as avg_salary
from salaries as a
where a.to_date = '9999-01-01' and a.salary not in
((select max(b.salary) from salaries as b where b.to_date = '9999-01-01'),
(select min(c.salary) from salaries as c where c.to_date = '9999-01-01'))
SQL249 分页查询employees表,每5行一页,返回第2页的数据
- 在 LIMIT X,Y 中,Y代表返回几条记录,X代表从第几条记录开始返回(第一条记录序号为0)。
select *
from employees
limit 5,5
- LIMIT 后的数字代表返回几条记录,OFFSET
后的数字代表从第几条记录开始返回(第一条记录序号为0),也可理解为跳过多少条记录后开始返回。
select *
from employees
limit 5
offset 5
SQL251 使用含有关键字exists查找未分配具体部门的员工的所有信息
- where语句排除掉已分配部门的就是未分配部门的了
select *
from employees as e
where not exists(
select emp_no from dept_emp where emp_no=e.emp_no
)
SQL253 获取有奖金的员工相关信息
- 当存在多种类型时,用case…when…end分情况解决
select
emp_no,
first_name,
last_name,
btype,
salary,
round((case btype
when 1 then salary*0.1
when 2 then salary*0.2
when 3 then salary*0.3
end) ,1)as bonus
from employees
join emp_bonus using(emp_no)
join salaries using(emp_no)
where to_date = '9999-01-01'
order by emp_no
SQL254 统计salarv的罗计和running total
- 窗口函数内的order by具有累加的效果
select
emp_no,
salary,
sum(salary)over(order by emp_no)as running_total
from salaries
where to_date = '9999-01-01'
SQL255 给出employees表中排名为奇数行的first name
- % 2 = 1:除以2余1 表示的是奇数
- where语句中的意思:a表中的第一个name大于等于b表中的m个name,那么count记为m;a表中的第二个name大于等于b表中的n个name,那么count记为n,依次类推。在比较的过程中,其实也完成了排序。
- 排序完,并且找到奇数后,直接select就能找到想要的结果。
select
first_name
from
employees as a
where(
select count(*) from employees as b
where a.first_name>=b.first_name
)%2 = 1
SQL256 出现三次以上相同积分的情况
- 要筛选某一字段出现的次数,先分组,再设置筛选条件,涉及到聚合函数,用having
select
number
from grade
group by number
having count(number)>=3