SQL 笔记合集:速查、练习题与数仓报表

37 章 SQL 笔记:基础与 Cookbook、31 组练习题、数仓报表与快手面试题,一次性收在一篇里。

本页目录37 节

练习提纲与总结

提纲

SQL题的练习
注意spark-SQL 和 HQL语法的区别
学习SQL中的技巧
训练一下

练习题来自网络和leedcode
还有把hive的复习纲要上面的函数与练习题都练习一遍
把数仓SQL题再写一遍
一共大致200道SQL题争取一个月内完成!!!!!

把一些反馈记录下来

2-3
1.写了30道SQL题发现的问题是懒惰,执行出错急于看答案,对于一些不会的题目脑子里没有印象,我应该再写一遍,继续总结.大部分题目都是简单题,我要做的是不会写的题目要有思路,而不是寻求答案,暂且,还有实践的空间

2-10
2.写了100道SQL题,发现leedcode的题目过于简单,比较难的题目就是题目难理解的题目了,
这些题目中,比较难的题目的解决思想有构造一个辅助表,0与union all row_number结合构造0-max的数,在having中使用聚合函数进行判断,构造一个tag,等量代换的解决方法,还有一个就是case when的巧妙应用,在leedcode篇章我会进行说明,还有要重点关注一类题型分类讨论:我对这类题目比较生疏
把题目刷完要注意结合实际业务对SQL进行复习和精进

2-11
3.leedcode全部的题目刷完,下一步梳理错题与总结SQL题的解题思路和方法
leedcode的高频题还没再写一遍:
下一个阶段的任务是
1.如上,继续发掘leedcode习题,完成高频题
2.写一篇博客总结SQL题的解题方法(2月底完成)
3.把牛客网错题总结一下,把互联网50题在写一遍,把数仓项目的SQL再写一遍

2-20
4.10天后我再一次写SQL题,这次写了20道题,梳理了一下了牛客网的题目,感觉进步很大,但是对having过滤的使用不够清晰,对序列号的处理不够清晰......

3-21
一个月后,基本上各种SQL题都做过了,提供一些较难的SQL题类型:left join 和 join 的选择问题,事实上并不简单,行转列/列转行的问题,涉及split,炸裂函数的使用我认为是较难的题目,以及复杂类型的处理:array/struct/map等处理起来还是细节性质的,最后是SQL中的数据倾斜问题应该怎么避免,SQL结构的优化问题

5-30
发现在SQL的处理上遇到了一些瓶颈了,对数据还是不怎么敏感,以及对时间的处理不是很擅长
最近要读一点数据分析的书籍了

8-12
SQL处理是掌握了,目前主要就是整理SQL与分类,上班其实没有什么SQL上的难点,主要就是对业务的理解,以及使用SQL来解决问题,因此下一步的重点是治理
我尝试一些SQL的优化方法,但是并没有取得什么关键的效果,知道和使用其实相差很大的

10-30
要关注一些多join连接的性能问题,高枚举值的Join连接性能问题
要关注一些sql的参数设置优化性能

2022-02-15

  1. 归因分析,漏斗分析,路径分析的设计方案
  2. 大表join大表的加速方案
  3. 加速明细表去重的问题
  4. 加速高基数维度的查询问题

把一些知识点记录下来

1.sum() 窗口自连接的实现
2.行转列的操作
3.avg() sum() 等窗口函数在同一个select中开窗,大小不同有妙用,解决了group by 字段维度不一致时要join的问题
4.注意null的处理,我要总结一下,还是不太明白
5.row_number() 和dense_rank() 的效率
6.中位数求法的妙用,使用两个序列函数asc desc来实现:题目:给定数字的频率查询中位数
7.union 和 or 哪个的效率高
8.SQL中,去重有哪些优化的方法
9.位运算的使用
10 where联合字段的使用
11.max等聚合函数与group by获取最大值的问题,使用窗口函数,或使用子查询获取每个组内的最大值,外边where联合字段查询并列情况
12.all关键字的使用
13.信息min/sum的开窗与题意的结合
14.注意没有主键情况下 != 尽量转化为 not in 等(采坑)
15.辨析left join 中条件过滤 on和where的区别
16.count():求1,id,出现的id出现的次数,不包含0
17.联合去重distinct
18.distinct与count()一起用采坑
19.分类讨论的解决方法
20.辅助表的构造方法
21.使用自连接,解决等量代换的问题
22.采用一个组内全局的count来获取,top问题
23.mysql中的function
24.hive中的分位函数和桶函数
25.14天趋势计算
26.同比计算的通用式
27.除数/被除数=0 的解决思路
28.数据倾斜的定位和真正的优化
29.同比报表化的SQL逻辑
30.不同计算引擎在null/0/NAN处理一致性方案

把一些总结记录下来

问题1:自连接问题
sum() 窗口的解决思路
序列函数(rank等) 实现思路
分组topN不用窗口怎么写

问题2:重点题
多条件过滤,总结篇第一题
用户购买平台
hapaer平台
查询球队积分

问题3:递归的问题

问题4.标签的问题

问题5.用基本的SQL语法来替换函数

问题6.多map嵌套下的同比计算解决方案

Cookbook:SQL 写法速查

总结的挺好的复制一下吧........

一.检索记录

1.1 从表中检索所有行和列

需要检索所有列,一般是直接用"*"来代表
需要注意如果是查看数据库中的数据可以用 星号来代替,如果是代码中,最好将每个列都列明,方便后面引用列。

代码:

sql
select * from emp

1.2 从表中检索部分行

使用where子句可以指定要保留哪些行。

例如要查看部门编号为10的所有员工:

sql
select * from emp where deptno = 10

1.3 查找满足多个条件的行

使用 where子句以及 OR 和 AND 子句。

例如,如果要查找部门10中所有员工,且有提成的员工

sql
select *
  from emp
 where deptno = 20
   and comm is not null

1.4 从表中检索部分列

指定感兴趣的列。

例如,如果只查看员工的名字、部门号和工资

sql
select ename,deptno,sal
  from emp

1.5 为列取有意义的名称

要改变查询结果列名,可以按这种格式使用AS关键字: 原名 AS 新名(一些数据库可以省略AS)

sql
select sal as salary, comm as commission
  from emp

1.6 在where子句中引用取别名的列

MySQL在where子句中引用取别名的列

1.7 连接列值

MySQL 连接列值

1.8 在select语句中使用条件逻辑

使用CASE 表达式 直接在 SELECT 语句中执行条件逻辑。

需求: 要产生一个结果集如果一个员工工资小于2000美金,就返回消息"UNDERPAID",如果大于等于4000美金,就返回消息"OVERPAID",如果在这两者之间,就返回"OK".

sql
select ename, sal,
       case when sal <= 2000 then 'UNDERPAID'
            when sal >= 4000 then 'OVERPAID'
            else 'OK'
        end as status
  from  emp

1.9 限制返回行数

限制查询中返回的行数,这里不关心顺序,返回任何n行都行。

sql
select * from emp limit 5

1.10 从表中随机返回n行数据

从表中随机返回n行数据

1.11 查找空值

要查找某列值为空的所有行。

要确定值是否为空,必须使用 IS NULL

sql
select * from emp where comm is null

1.12 将空值转为实际值

在一些行中包含空值,需要使用非空值来代替这些空值。

使用coalesce函数用实际的值替换控制,coalesce函数有1个或多个参数,改函数返回第一个非空值。

sql
select coalesce(comm,0) from emp

1.13 按模式搜索

需求: 在部门10和部门20,需要返回名字中有一个 "I" 或者职务(job title)中带有 "ER" 的员工。

使用LIKE运算符和SQL通配符"%"

sql
select ename, job
  from emp
 where deptno in (10,20)
   and (ename like '%I' or job like '%ER')

二.查询结果排序

2.1 以指定的次序返回查询结果

需求: 显示部门10中员工名字、职位和工资,并按照工资的升序排列。

使用ORDER BY 子句可以对结果集进行排序。解决方案按SAL升序对行进行排列。
默认情况下,ORDER BY以升序方式排列,因此ASC子句是可选的。DESC表示降序排列。

sql
select ename, job, sal
  from emp
 where deptno = 10
 order by sal asc;

-- 等同于
select ename, job, sal
  from emp
 where deptno = 10
 order by 3 asc;

2.2 按多个字段排序

需求: 在EMP表中,首先按照DEPTNO的升序排序行,然后按照工资的降序排列。

在ORDER BY子句中列出不同的排序列,使用逗号分隔:

sql
select empno,deptno,sal,ename,job
  from emp
 order by deptno, sal desc

2.3 按子串排序

需求: 按字符串的某一部分对查询结果集排序,要从EMP表中返回员工名字和职位,并且按照职位字段的最后两个字符排序。

在ORDER BY子句中使用SUBSTR函数:

sql
select ename,job
  from emp
 order by substr(job,length(job)-2)

2.4 处理排序的空值

需求: 在EMP中根据COMM排序结果。但是,这个字段可以有空值,需要指定是否将空值排在最后。

sql
select ename,sal,comm
  from (
select ename,sal,comm,
       case when comm is null then 0 else 1 end as is_null
  from emp
       ) x
 order by is_null,comm desc

2.5 根据数据项的键排序

MySQL根据数据项的键排序

三.操作多个表

3.1 记录集的叠加

需求: 要将来自多个表的数据组织到一起,就想将一个结果集叠加到另一个上面一样。这些表不必有相同的关机子,但是,他们对应累的数据类型应相同。

例如,要显示EMP表部门10中员工的名字和部门编号,以及DEPT表中每个部门的名字和部门编号。

使用集合操作 UNION ALL把多个表中的行组合到一起

sql
select ename as ename_and_dname, deptno
  from emp
 where deptno = 10
union all
select '----------', null
union all
select dname,deptno
  from dept

3.2 组合相关的行

需求: 多个表有一些相同的列,或有些列的值相同,要通过连接这些列得到结果。

例如:要显示部门10中所有员工的名字,以及每个员工所在部门的工作地点,这些数据存储在两个独立的表中

sql
select e.ename, d.loc
  from emp e, dept d
 where e.deptno = d.deptno
   and e.deptno = 10;

-- 等同于
select e.ename, d.loc
  from emp e
 inner join dept d
 on e.deptno = d.deptno
 where e.deptno = 10;

讨论
该解决方案是连接的一种,更准确地说是等值连接,这是内连接(inner join)的一种类型。
连接操作会将来自两个表的行组合到一个表中。等值连接的嵌套条件是相同条件。

从概念上来说,要得到连接的结果集,首先要创建from子句后列出的表的笛卡尔积(所有可能的情况)

sql
select e.ename, d.loc,
       e.deptno as emp_deptno,
       d.deptno as dept_deptno
  from emp e, dept d
 where e.deptno = 10

笛卡尔积:

sql
mysql> select e.ename, d.loc,
    ->        e.deptno as emp_deptno,
    ->        d.deptno as dept_deptno
    ->   from emp e, dept d
    ->  where e.deptno = 10;
+--------+----------+------------+-------------+
| ename  | loc      | emp_deptno | dept_deptno |
+--------+----------+------------+-------------+
| CLARK  | NEW YORK |         10 |          10 |
| KING   | NEW YORK |         10 |          10 |
| MILLER | NEW YORK |         10 |          10 |
| CLARK  | DALLAS   |         10 |          20 |
| KING   | DALLAS   |         10 |          20 |
| MILLER | DALLAS   |         10 |          20 |
| CLARK  | CHICAGO  |         10 |          30 |
| KING   | CHICAGO  |         10 |          30 |
| MILLER | CHICAGO  |         10 |          30 |
| CLARK  | BOSTON   |         10 |          40 |
| KING   | BOSTON   |         10 |          40 |
| MILLER | BOSTON   |         10 |          40 |
+--------+----------+------------+-------------+
12 rows in set (0.01 sec)

这将返回表EMP部门10中所有员工,以及DEPT的所有部门。
然后,在WHERE子句的表达式中使用 e.deptno 和 d.deptno 来限制结果集,只返回EMP.DEPTNo和DEPT.DEPTNO相等的那些行。

sql
select e.ename, d.loc
  from emp e, dept d
 where e.deptno = d.deptno
   and e.deptno = 10;

测试记录:

sql
mysql> select e.ename, d.loc
    ->   from emp e, dept d
    ->  where e.deptno = d.deptno
    ->    and e.deptno = 10;
+--------+----------+
| ename  | loc      |
+--------+----------+
| CLARK  | NEW YORK |
| KING   | NEW YORK |
| MILLER | NEW YORK |
+--------+----------+
3 rows in set (0.00 sec)

mysql>

3.3 在两个表中查找相同的行

需求:
查找两个表中共同行,但有多列可以用来连接这两个表。

sql
create view v_test2
as
select ename,job,sal
  from emp
 where job = 'CLERK'

要返回正确的结果,必须按所有必要的列进行连接。或者,如果不想进行连接,也可以使用子查询 in 。

sql
select e.ename,e.job,e.sal
  from emp e,v_test2 v
 where e.ename = v.ename
   and e.job = v.job
   and e.sal = v.sal;

select ename,job,sal
  from emp
 where (ename,job,sal) in
 (select ename,job,sal from v_test2);

3.4 从一个表中找到另一个表中没有的值

需求:
要从一个表(称为源表)中查找在另一目标表中不存在的值。

例如,要从表DEPT中查找在表EMP中不存在的数据的所有部门。
在示例数据库中,DEPTNO值为40的记录在表EMP中不存在。

MySQL可以使用not in

sql
select deptno
  from dept
 where deptno not in (select deptno from emp);

不过not in 存在一个问题
如果not in 后面的结果集中有null的话,前面的查询结果会返回所有的值。

sql
select deptno
  from dept 
 where deptno not in (10 ,20, null);

测试记录:

sql
mysql> select deptno
    ->   from dept
    ->  where deptno not in (10 ,20, null);
Empty set (0.00 sec)

mysql>

deptno not in (10,20,null)等同于:
not (deptno = 10 or deptno = 50 or deptno = null)

(false or fasle or null) 最后的结果为null,所以不会有什么输出

此时可以把not in 改为not exists可以避免上述问题

sql
select deptno
  from dept d
 where not exists (select 1 from emp e where e.deptno = d.deptno );

3.5 在一个表中查找与其它表不匹配的记录

需求:
对于具有相同关键字的两个表,要在一个表中查找与另外一个表中不匹配的行。
例如: 要查找没有支援的部门

解决方案:
首先返回一个表中的所有行,以及另一个表中与公共列匹配的行或不存在匹配行,然后,仅保留不匹配的行。

sql
select d.*
  from dept d
  left join emp e
  on (d.deptno = e.deptno)
 where e.deptno is null;

3.6 像查询中增加连接而不影响其它连接

emp_bonus表:

sql
create table emp_bonus(empno int,received date,type int);

insert into emp_bonus(empno,received,type) values (7369,'2005-03-14',1);
insert into emp_bonus(empno,received,type) values (7900,'2005-03-14',2);
insert into emp_bonus(empno,received,type) values (7788,'2005-03-14',3);

问题:
已经有了一个查询可以返回所需要的值,还需要得到其他信息,但当加入这些信息时,发现原始结果集中的数据有丢失。

例如,要返回所有的员工信息、他们工作部门的地点及所获得的奖励。
要求将每个员工说获得的奖励的日期列加入到结果数据中,但是连接到emp_bonus表后,所返回的记录数要比所希望的要少,因为并不是每个员工都有奖励。

sql
select e.ename, d.loc
  from emp e, dept d
 where e.deptno = d.deptno;

解决方案:
可以使用外连接来获取这些附加的信息,并且原始查询中的数据不会丢失。

sql
select e.ename, d.loc,eb.received
  from emp e
 inner join dept d
   on e.deptno = d.deptno
 left join emp_bonus eb
   on e.empno = eb.empno
 order by 2;

其实也可以使用标量子查询

sql
select e.ename, 
       d.loc,
       (select eb.received from emp_bonus eb where eb.empno = e.empno) as received
  from emp e, dept d
 where e.deptno = d.deptno
 order by 2;

3.7 检测两个表中是否有相同数据

检测两个表中是否有相同数据

3.8 识别和消除笛卡尔积

需求:
要返回在部门10中每个员工的姓名,以及部门的工作地点

sql
select e.ename, d.loc
  from emp e, dept d
 where e.deptno = 10

测试记录:

sql
mysql> select e.ename, d.loc
    ->   from emp e, dept d
    ->  where e.deptno = 10;
+--------+----------+
| ename  | loc      |
+--------+----------+
| CLARK  | NEW YORK |
| KING   | NEW YORK |
| MILLER | NEW YORK |
| CLARK  | DALLAS   |
| KING   | DALLAS   |
| MILLER | DALLAS   |
| CLARK  | CHICAGO  |
| KING   | CHICAGO  |
| MILLER | CHICAGO  |
| CLARK  | BOSTON   |
| KING   | BOSTON   |
| MILLER | BOSTON   |
+--------+----------+
12 rows in set (0.00 sec)

可以看到多了很多不必要的输出,因为忘记写表连接条件了
emp表4条记录,dept表3条记录,笛卡尔积产生的数据就是4*3=12条

其实真正需要的输出是4条

解决方案:
在from子句对表进行连接来返回正确的结果集:

sql
select e.ename, d.loc
  from emp e, dept d
 where e.deptno = 10
   and d.deptno = e.deptno;

3.9 聚集与连接

emp_bonus表:

sql
create table emp_bonus(empno int,received date,type int);

insert into emp_bonus(empno,received,type) values (7934,'2005-03-17',1);
insert into emp_bonus(empno,received,type) values (7934,'2005-09-15',2);
insert into emp_bonus(empno,received,type) values (7839,'2005-09-15',3);
insert into emp_bonus(empno,received,type) values (7782,'2005-09-15',1);

需求:
要在包含多个表的查询中执行聚集运算,要确保表间连接不能使聚集运算发生错误。

例如,要查找在部门10中所有员工的工资合计和奖金合计。由于有些员工的工资的奖金纪录不止一条,在表EMP表EMP_BONUS之间做连接会导致聚集函数SUM算得的值错误。

解决方案:
当处理聚集与连接混合操作时,一定要小心。如果连接产生重复行,可以有两种方法来避免聚集函数计算错误:

方法1:
只要在调用聚集函数时使用关键字DISTINCT,这样每个值只能参与计算一次

方法2:
在进行连接操作前前先执行聚集操作(在内联视图中),这样,因为聚集计算已经在进行连接前完成了,所以可以避免聚集函数计算有误,可以规避此类问题。

方法1使用distinct,个人感觉存在问题,如果真有不同员工的工资相同,会少计算了

sql
select  deptno,
        sum(distinct sal) as total_sal,
        sum(bonus) as total_bonus
  from  (
select  e.empno,
        e.ename,
        e.sal,
        e.deptno,
        e.sal* case when eb.type = 1 then 0.1 when eb.type =2 then 0.2 else 0.3 end as bonus
  from  emp e, emp_bonus eb
 where  e.empno = eb.empno
   and  e.deptno = 10
) x
 group by deptno;

方法2在表连接在聚集运算之前

sql
select d.deptno,
       d.total_sal,
       sum(e.sal*case when eb.type = 1 then 0.1 when eb.type =2 then 0.2 else 0.3 end) as bonus
  from emp e,
       emp_bonus eb,
       (
select deptno, sum(sal) as total_sal
  from emp
 where deptno = 10
 group by deptno
       ) d
 where e.deptno = d.deptno
   and e.empno = eb.empno
 group by d.deptno,d.total_sal; 

3.10 聚集与外连接

emp_bonus表:

sql
create table emp_bonus(empno int,received date,type int);

insert into emp_bonus(empno,received,type) values (7934,'2005-03-17',1);
insert into emp_bonus(empno,received,type) values (7934,'2005-09-15',2);

方法1使用distinct,个人感觉存在问题,如果真有不同员工的工资相同,会少计算了

sql
select  deptno,
        sum(distinct sal) as total_sal,
        sum(bonus) as total_bonus
  from  (
select  e.empno,
        e.ename,
        e.sal,
        e.deptno,
        e.sal* case when eb.type = 1 then 0.1 when eb.type =2 then 0.2 when eb.type =3 then 0.3 end as bonus
  from  emp e
  left join emp_bonus eb
    on  e.empno = eb.empno
  where 1 = 1
   and  e.deptno = 10
) x
 group by deptno;

方法2在表连接在聚集运算之前

sql
select d.deptno,
       d.total_sal,
       sum(e.sal*case when eb.type = 1 then 0.1 when eb.type =2 then 0.2 else 0.3 end) as bonus
  from emp e,
       emp_bonus eb,
       (
select deptno, sum(sal) as total_sal
  from emp
 where deptno = 10
 group by deptno
       ) d
 where e.deptno = d.deptno
   and e.empno = eb.empno
 group by d.deptno,d.total_sal; 

3.11 从多个表中返回丢失的数据

此处解决方案是full out join全连接

参考之前写的表连接的blog:
MySQL表连接小结

3.12 在运算和比较时使用null值

需求:
NULL值永远不会等于或不等于任何值,也不等于NULL值自己,但是需要像计算真实值一样计算可为空的返回值。

例如,需要在表EMP中查出所有比"WARD"提成(COMM)低的员工,提成为NULL(空)的员工也应当包括在其中。

解决方案:
使用COALESCE函数将NULL值转换为一个可以用来作为标准值进行比较的真实值:

sql
select ename,comm
  from emp
 where coalesce(comm,0) < ( select comm
                             from  emp
                            where  ename = 'WARD')

四.插入、更新与删除

4.1 插入新纪录

需求:
像表中插入一条新的记录。

例如,要想DEPT表中插入一条新的记录。其中,DEPTNO值为50、DNAME的值为"PROGRAMMING"、LOC的值为"BALTIMORE"

解决方案:
使用VALUES子句的INSERT语句来插入一行:

sql
insert into dept (deptno,dname,loc)
 values (50,'PROGRAMMING','BALTIMORE');

对于MySQL,可以选择一次插入一行,或者用多个值列表一次插入多行:

sql
/* multi row insert */
insert into dept (deptno,dname,loc)
 values (1,'A','B'),
        (2,'C','D');

4.2 插入默认值

需求:
定义表时可以为某些列定义默认值。现要以默认值插入一行,而无需指定各列的值。

sql
create table D (id int default 0,name varchar(20));

解决方案:
插入语句可以直接用default或者不指定

sql
insert into D (id, name) values (default, 'test1');
insert into D (name) values ('test2');

4.3 使用NULL代替默认值

需求:
在一个定义了默认值的列插入数据,并且需要不管该列的默认值是什么,都将该列值设为null

sql
create table D ( id int default 0, name varchar(10));

解决方案:
可以在值列表中明确地指定NULL值

sql
insert into d (id, name) values (null, 'test3');

4.4 从一个表向另外的表中复制行

sql
create table DEPT_EAST like dept;

需求:
要使用查询从一个表中向另外的表中富支行。该查询可能非常复杂,也可能非常简单,但是最终是需要将查询的结果插入到其它的表中。

例如,要将表dept中的行复制到表DEPT_EAST中。

解决方案:
说使用的方法就是在INSERT语句后面紧跟一个用来产生说要插入的行的查询:

sql
insert into dept_east(deptno, dname,loc)
select deptno,dname,loc
  from dept
 where loc in ('NEW YORK','BOSTON');

4.5 复制表定义

需求:
要创建新表,该表与已有表的列设置相同。

例如,想要创建一个DEPT表的副本,名为DEPT_1,但只是想复杂表结构而不想要复制源表中的记录。

解决方案:
可以使用CTAS命令,也可以使用like命令

sql
create table dept_1 as select * from dept where 1 = 0;

create table dept_2 like dept;

查看表结构:

sql
mysql> show create table dept_1\G
*************************** 1. row ***************************
       Table: dept_1
Create Table: CREATE TABLE `dept_1` (
  `deptno` int NOT NULL,
  `dname` varchar(14) DEFAULT NULL,
  `loc` varchar(13) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> show create table dept_2\G
*************************** 1. row ***************************
       Table: dept_2
Create Table: CREATE TABLE `dept_2` (
  `deptno` int NOT NULL,
  `dname` varchar(14) DEFAULT NULL,
  `loc` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`deptno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql>

4.6 一次性向多个表中插入记录

目前MySQL还不支持此功能

目前Oracle、DB2、Hive支持此功能,但是实现方式不同。

4.7 阻止对某几列插入

阻止对某几列插入

4.8 在表中编辑纪录

问题:
要修改表中某写(或全部)行的值。

例如,可能想要将部门20中所有员工的工资增加10%。

解决方案:
使用Update语句来修改数据库表中已有行。

sql
update emp
   set sal = sal * 1.1
  where deptno = 20;

4.9 当相应行存在时更新

sql
create table emp_bonus(empno int,received date,type int);

insert into emp_bonus(empno,received,type) values (7369,'2005-03-14',1);
insert into emp_bonus(empno,received,type) values (7900,'2005-03-14',2);
insert into emp_bonus(empno,received,type) values (7788,'2005-03-14',3);

问题:
仅当另一个表中相应的行存在时,更新某表中的一些行。

例如,如果表emp_bonus中存在某位员工,则要将该员工的工资增加20%(在表emp中)。

解决方案:
可以在where子句中结合子查询使用

sql
update emp
   set sal = sal* 1.2
 where empno in (select empno from emp_bonus);

4.10 用其它表中的值更新

用其它表中的值更新

4.11 合并记录

目前只有Oracle的merge语句可以解决此类问题。
MySQL暂不支持此类需求。

4.12 从表中删除所有记录

sql
delete from emp;

4.13 删除指定记录

sql
delete from emp where deptno = 10;

4.14 删除单个记录

从表中删除单个记录,一般需要找到表的主键列,然后根据主键列进行删除。

sql
delete from emp where empno = 7369;

4.15 删除违反参照完整性的记录

例如,需要删除emp表中deptno在dept表中不存在的记录。

此时可以使用not exists来解决。

sql
delete from emp
 where not exists (
   select 1 from dept 
     where dept.deptno = emp.deptno
   );

4.16 删除重复记录

sql
create table test_repeat(id int,name varchar(20),mobile varchar(20));

insert into test_repeat(id ,name, mobile) values (1,'A','123456');
insert into test_repeat(id ,name, mobile) values (2,'B','123456');
insert into test_repeat(id ,name, mobile) values (3,'C','123456');
insert into test_repeat(id ,name, mobile) values (4,'A','123456');
insert into test_repeat(id ,name, mobile) values (5,'A','123456');
insert into test_repeat(id ,name, mobile) values (6,'B','123456');

需要删除重复记录,此时可以根据其它列进行分组,然后保留主键id列最大的一条记录。

sql
delete from test_repeat
  where id not in 
      ( select max_id from 
      (  select max(id) as max_id from test_repeat group by name,mobile) tmp );

测试记录:

sql
mysql> select * from test_repeat;
+------+------+--------+
| id   | name | mobile |
+------+------+--------+
|    1 | A    | 123456 |
|    2 | B    | 123456 |
|    3 | C    | 123456 |
|    4 | A    | 123456 |
|    5 | A    | 123456 |
|    6 | B    | 123456 |
+------+------+--------+
6 rows in set (0.00 sec)
mysql> delete from test_repeat
    ->   where id not in
    ->       ( select max_id from
    ->       (  select max(id) as max_id from test_repeat group by name,mobile) tmp );
Query OK, 3 rows affected (0.01 sec)

mysql> select * from test_repeat;
+------+------+--------+
| id   | name | mobile |
+------+------+--------+
|    3 | C    | 123456 |
|    5 | A    | 123456 |
|    6 | B    | 123456 |
+------+------+--------+
3 rows in set (0.00 sec)

mysql>

4.17 删除从其它表引用的记录

需求:
从一个表中删除被另一个表应用的记录。

考虑下面的dept_accidents表,其中每行代表生产过程中的一次失误,每行中记录了事故发生的部门以及事故类型。

sql
create table dept_accidents
( deptno    int,
  accident_name varchar(20) );

insert into dept_accidents values (10, 'BROKEN FOOT');
insert into dept_accidents values (10, 'FLESH WOUND');
insert into dept_accidents values (20, 'FIRE');
insert into dept_accidents values (20, 'FIRE');
insert into dept_accidents values (20, 'FLOOD');
insert into dept_accidents values (30, 'BRUISED GLUTE');

要从表EMP中删除所在部门已经发生了三次以上的事务的所有员工的记录。

解决方案:
使用子查询和聚集函数count来查找出发生三次事故以上的部门,然后将这些部门的员工全部删除。

sql
delete from emp
 where deptno in ( select deptno 
                     from dept_accidents
                    group by deptno
                   having count(*) >= 3 );

五.元数据查询

元数据查询

包含5.1到5.4章节

5.1 列出模式的表

sql
select table_name
from information_schema.tables
where table_schema = 'ZQS';

5.2 列出表的列

sql
select column_name,data_type,ordinal_position
from information_schema.columns
where table_schema = 'ZQS'
and   table_name = 'EMP';

5.3 列出表的索引列

sql
show index from emp\G

5.4 列出表的约束

sql
select  a.table_name,
        a.constraint_name,
        b.column_name,
        a.constraint_type
from information_schema.table_constraints a,
     information_schema.key_column_usage b
where a.table_name = 'EMP'
and   a.table_schema  = 'ZQS'
and   a.table_name = b.table_name
and   a.table_schema = b.table_schema
and   a.constraint_name = b.constraint_name;

5.5 列出没有相应索引的外键

可以使用 SHOW INDEX 命令来检查索引信息,例如索引名,在索引中的列和在索引中这些列的顺序。
另外,可以查询INFORMATION_SCHEMA.KEY_COLUMN_USAGE列出指定表的外键。

在MySQL 5中,外键号称可以自动索引,但事实上是可以解除索引的。

要检测外键索引是否被解除,可以对该表执行 SHOW INDEX命令,并且将结果跟INFORMATION_SCHEMA.KEY_COLUMN_USAGE.COLUMN_NAME中同一个表的结果相比,如果KEY_COLUMN_USAGE中有COLUMN_NAME,但SHOW INDEX的结果中没有,则该列没有被索引。

5.6 使用SQL来生成SQL

使用SQL来生成SQL

六.使用字符串

6.1 遍历字符串

MySQL 遍历字符串

6.2 字符串文字中包含引号

字符串中包含引号

6.3 计算字符在字符串中出现的次数

计算字符在字符串中出现的次数

6.4 从字符串中删除不需要的字符

从字符串中删除不需要的字符

6.5 将字符串和数字数据分离

此解决方案需要使用到translate,MySQL暂时不支持

6.6 判断字符串是不是数字字符类型

判断字符串是不是数字字符类型

6.7 提取姓名大写首字母缩写

提取姓名大写首字母缩写

6.8 按字符串中的部分内容排序

前面章节已经涉及
order by substr(col_name,length(col_name) - 2)

6.9 按字符串中的数值排序

此解决方案需要使用到translate,MySQL暂时不支持

6.10 根据表中的行创建一个分隔列表

根据表中的行创建一个分隔列表

6.11 将分隔数据转换为多值IN列表

将分隔数据转换为多值IN列表

6.12 按字母顺序排列其中的各个字符

按字母顺序排列其中的各个字符

6.13 判别可以作为数值的字符串

提取字符和数字里面的数字

6.14 提取第n个分隔的子串

需求:
从字符串中提取出一个指定的、由分隔符隔开的子字符串。

例如,去除每行中第二个姓名。

sql
create view V as
select 'mo,larry,curly' as name
union all
select 'tina,gina,jaunita,regina,leena' as name;

drop table if exists t10;

create table t10(id int);

insert into t10 values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);

解决方案:
解决此问题的关键就是将每个姓名作为单独的行返回,并保留每个姓名在列表中的顺序。

sql
select v.name,
       t10.id,
       substring_index(v.name,',',t10.id) as middle_name,
       substring_index(substring_index(v.name,',',t10.id),',',-1)  as new_name
  from V
 inner join t10
 on t10.id <= length(v.name) - length(replace(v.name,',','')) + 1 
 order by v.name,t10.id;

测试记录:

sql
mysql> select v.name,
    ->        t10.id,
    ->        substring_index(v.name,',',t10.id) as middle_name,
    ->        substring_index(substring_index(v.name,',',t10.id),',',-1)  as new_name
    ->   from V
    ->  inner join t10
    ->  on t10.id <= length(v.name) - length(replace(v.name,',','')) + 1
    ->  order by v.name,t10.id;
+--------------------------------+------+--------------------------------+----------+
| name                           | id   | middle_name                    | new_name |
+--------------------------------+------+--------------------------------+----------+
| mo,larry,curly                 |    1 | mo                             | mo       |
| mo,larry,curly                 |    2 | mo,larry                       | larry    |
| mo,larry,curly                 |    3 | mo,larry,curly                 | curly    |
| tina,gina,jaunita,regina,leena |    1 | tina                           | tina     |
| tina,gina,jaunita,regina,leena |    2 | tina,gina                      | gina     |
| tina,gina,jaunita,regina,leena |    3 | tina,gina,jaunita              | jaunita  |
| tina,gina,jaunita,regina,leena |    4 | tina,gina,jaunita,regina       | regina   |
| tina,gina,jaunita,regina,leena |    5 | tina,gina,jaunita,regina,leena | leena    |
+--------------------------------+------+--------------------------------+----------+
8 rows in set (0.00 sec)

6.15 分解IP地址

分解IP地址

七.使用数字

7.1 计算平均值

sql
select avg(sal) from emp;

7.2 求某列的最小/最大值

sql
select min(sal) as min_sal,max(sal) as max_sal from emp;

7.3 对某列的值求和

sql
select sum(sal) from emp ;

select deptno,sum(sal) from emp group by deptno;

7.4 求一个表的行数

sql
select count(*) from emp;

select deptno,count(*) from emp group by deptno;

7.5 求某列值的个数

求某列值的个数

7.6 生成累计和

生成累计和

7.7 生成累计乘积

生成累计乘积

7.8 计算累积差

MySQL 生成累计差

7.9 计算模式

需求:
查找某个列中值的模式(数学中的模式概念就是对于给定的数据集出现最频繁的元素)。

例如,查找deptno 20中工资的模式。

解决方案:

sql
select sal
 from 
  (
select sal,
       dense_rank() over (order by cnt desc) as rnk
  from (
select sal,count(*) as cnt
  from emp
 where deptno = 20
 group by sal
       ) x
  ) y
 where rnk = 1

7.10 计算中间值

计算中间值

7.11 求总和的百分比

sql
select (sum(
         case when deptno = 10 then sal end)/ sum(sal)
       )*100 as pct
  from emp;

7.12 对可空列做聚集

对空值做聚集的时候,最好将空值转为0,不然会影响到平均值的计算。

sql
select avg(coalesce(comm,0)) as avg_comm from emp where deptno = 30;

测试记录:

sql
mysql> select ename,comm from emp where deptno = 30;
+--------+---------+
| ename  | comm    |
+--------+---------+
| ALLEN  |  700.00 |
| WARD   |  500.00 |
| MARTIN | 1400.00 |
| BLAKE  |    NULL |
| TURNER |    0.00 |
| JAMES  |    NULL |
+--------+---------+
6 rows in set (0.00 sec)

mysql> select avg(comm) from emp where deptno = 30;
+------------+
| avg(comm)  |
+------------+
| 650.000000 |
+------------+
1 row in set (0.00 sec)

mysql> select avg(coalesce(comm,0)) as avg_comm from emp where deptno = 30;
+------------+
| avg_comm   |
+------------+
| 433.333333 |
+------------+
1 row in set (0.00 sec)

mysql>

7.13 计算不包含最大值和最小值的均值

计算不包含最大值和最小值的均值

7.14 把字母数字串转换为数值

MySQL目前不支持translate函数,暂时无解决方案。

7.15 更改累积和中的值

问题:
根据另一列中的值修改累计和中的值。

假设一个场景,要显示信用卡账号的事务处理历史遗迹每次事务处理之后的当前余额。

sql
create view v (id,amt,trx)
as
select 1, 100 , '存款'
union all
select 2, 100 , '存款'
union all
select 3, 50 , '取款'
union all
select 4, 100 , '存款'
union all
select 5, 200 , '取款'
union all
select 6, 50 , '取款'

解决方案:
使用标量子查询创建累计和,并使用CASE表达式判断事务处理的类型

sql
select  id,
        amt,
        trx,
        sum(new_amt) over (order by id)  as balance
  from 
 (
select  case when v.trx = '取款' then -amt
             when v.trx = '存款' then amt
        else null end as new_amt,
        id,
        amt,
        trx
  from v
) tmp1;

测试记录:

sql
mysql> select  id,
    ->         amt,
    ->         trx,
    ->         sum(new_amt) over (order by id)  as balance
    ->   from
    ->  (
    -> select  case when v.trx = '取款' then -amt
    ->              when v.trx = '存款' then amt
    ->         else null end as new_amt,
    ->         id,
    ->         amt,
    ->         trx
    ->   from v
    -> ) tmp1;
+----+-----+--------+---------+
| id | amt | trx    | balance |
+----+-----+--------+---------+
|  1 | 100 | 存款   |     100 |
|  2 | 100 | 存款   |     200 |
|  3 |  50 | 取款   |     150 |
|  4 | 100 | 存款   |     250 |
|  5 | 200 | 取款   |      50 |
|  6 |  50 | 取款   |       0 |
+----+-----+--------+---------+
6 rows in set (0.00 sec)

八.日期运算

8.1 加减日、月、年

sql
select hiredate - interval 5 day     as d_minus_5d,
       hiredate + interval 5 day     as d_plus_5D,
       hiredate - interval 5 month   as d_minus_5M,
       hiredate + interval 5 month   as d_plus_5M,
       hiredate - interval 5 year    as d_minus_5Y,
       hiredate + interval 5 year    as d_plus_5Y
  from emp
 where deptno = 10;

8.2 计算两个日期之间的天数

sql
select ward_hd,allen_hd,datediff(ward_hd,allen_hd)
  from (
select hiredate as ward_hd
  from emp
 where ename = 'WARD'
       ) x,
       (
select hiredate as allen_hd
  from emp 
 where ename = 'ALLEN'
       ) y

8.3 确定两个日期之间工作日数目

weekday 返回数值的星期数
0 = Monday, 1 = Tuesday, … 6 = Sunday
根据这个剔除,然后count(*) 求总数即可

8.4 确定两个日期之间的月份数或年数

sql
select mnth, mnth/12
  from (
select (year(max_hd) - year(min_hd)) *12 +
        (month(max_hd) - month(min_hd)) as mnth
  from (
select min(hiredate) as min_hd, max(hiredate) as max_hd
  from emp
       ) x
       ) y;

8.5 确定两个日期之间秒、分、小时数

sql
select datediff(ward_hd,allen_hd)*24 hr,
       datediff(ward_hd,allen_hd)*24*60 min,
       datediff(ward_hd,allen_hd)*24*60*60 sec
  from (
select max(case when ename = 'WARD'
                then hiredate
           end) as ward_hd,
       max(case when ename = 'ALLEN'
                then hiredate
           end) as allen_hd
  from emp
       ) x

8.6 计算一年中周内各日期次数

生成包含一年的所有日期

使用DATE_FORMAT函数,确定每个日期为星期几,然后计算周内各日期的次数。

sql
with recursive c(n) as
(
 select 1 
 union all
 select n + 1  from c where n < 400
),
tmp1 as
(
select '2021-01-01' as dt 
),
tmp2 as
(
select adddate(dt,n-1) dt
  from tmp1
inner join c
)
select date_format(dt,'%a'),
       count(*)
  from tmp2
where dt < '2022-01-01'
group by date_format(dt,'%a')

8.7 确定当前记录和下一条记录之间相差的天数

问题:
求两个日期之间相差的天数。

例如,对于deptno 10中的每个员工,确定聘用他们的日期及聘用下一个员工的日期之间相差的天数。

解决方案:
这个问题的解决方案是找到当前员工聘用的最早hiredate,再来求差。

sql
select x.*,
       datediff(x.next_hd,x.hiredate) diff
  from (
select e.deptno, e.ename, e.hiredate,
       (select min(d.hiredate) from emp d
         where d.hiredate > e.hiredate) next_hd
  from emp e
 where e.deptno = 10
       ) x;

九.日期操作

9.1 确定一年是否为闰年

计算今年是否为闰年

9.2 确定一年内的天数

计算本年的天数

9.3 从日期中提取时间的各部分

sql
select date_format(current_timestamp,'%k') hr,
       date_format(current_timestamp,'%i') min,
       date_format(current_timestamp,'%s') sec,
       date_format(current_timestamp,'%d') dy,
       date_format(current_timestamp,'%m') mon,
       date_format(current_timestamp,'%Y') yr;

9.4 确定某个月的第一天和最后一天

计算本月的第一天及最后一天

9.5 确定一年内属于周内某一天的所有日期

sql
with recursive c(n) as
(
 select 1 
 union all
 select n + 1  from c where n < 400
),
tmp1 as
(
select '2021-01-01' as dt 
),
tmp2 as
(
select adddate(dt,n-1) dt
  from tmp1
inner join c
)
select dt,
       date_format(dt,'%a') week
  from tmp2
where dt < '2022-01-01'
  and date_format(dt,'%a') = 'Fri'
order by dt;

9.6 确定某月内第一个和最后一个"周内某天"的日期

计算本月的第一个和最后一个周一

9.7 创建日历

打印本月日历

9.8 列出一年中每个季度的开始日期和结束日期

sql
select quarter(adddate(dy,-1)) qtr,
       date_add(dy,interval -3 month) q_start,
       adddate(dy,-1) q_end
  from (
select date_add(dy,interval (3*id) month) dy
  from (
select id,
       adddate(current_date,-dayofyear(current_date) + 1 ) dy
  from t10
 where id <= 4
       ) x
       ) y;

测试记录:

sql
mysql> select quarter(adddate(dy,-1)) qtr,
    ->        date_add(dy,interval -3 month) q_start,
    ->        adddate(dy,-1) q_end
    ->   from (
    -> select date_add(dy,interval (3*id) month) dy
    ->   from (
    -> select id,
    ->        adddate(current_date,-dayofyear(current_date) + 1 ) dy
    ->   from t10
    ->  where id <= 4
    ->        ) x
    ->        ) y;
+------+------------+------------+
| qtr  | q_start    | q_end      |
+------+------------+------------+
|    1 | 2021-01-01 | 2021-03-31 |
|    2 | 2021-04-01 | 2021-06-30 |
|    3 | 2021-07-01 | 2021-09-30 |
|    4 | 2021-10-01 | 2021-12-31 |
+------+------------+------------+
4 rows in set (0.00 sec)

9.9 确定某个给定季度的开始日期和结束日期

下面这个sql输出还是存在一点问题

sql
select date_add(adddate(q_start,-day(q_start)+1) , interval -2 month) q_start,
       q_end
  from 
  (
select date_format(q_end,'%Y-%m-%d') as q_start,
       q_end 
  from (
select last_day(
       str_to_date(
          concat(
          substr(yrq,1,4), mod(yrq,10)*3), '%Y%m')) as q_end
  from (
select 20211 as yrq union all
select 20212 as yrq union all
select 20213 as yrq union all
select 20214 as yrq 
       ) x
       ) y
       ) z

测试记录:

sql
mysql> select date_add(
    ->        adddate(q_end,-day(q_end)+1),
    ->                interval -2 month) q_start,
    ->        q_end
    ->   from (
    -> select last_day(
    ->        str_to_date(
    ->           concat(
    ->           substr(yrq,1,4), mod(yrq,10)*3), '%Y%m')) q_end
    ->   from (
    -> select 20211 as yrq union all
    -> select 20212 as yrq union all
    -> select 20213 as yrq union all
    -> select 20214 as yrq
    ->        ) x
    ->        ) y
    ->       ;
+---------+------------+
| q_start | q_end      |
+---------+------------+
| NULL    | 2021-03-31 |
| NULL    | 2021-06-30 |
| NULL    | 2021-09-30 |
| NULL    | 2021-12-31 |
+---------+------------+
4 rows in set, 4 warnings (0.00 sec)

mysql> select date_add(adddate(q_start,-day(q_start)+1) , interval -2 month) q_start,
    ->        q_end
    ->   from
    ->   (
    -> select date_format(q_end,'%Y-%m-%d') as q_start,
    ->        q_end
    ->   from (
    -> select last_day(
    ->        str_to_date(
    ->           concat(
    ->           substr(yrq,1,4), mod(yrq,10)*3), '%Y%m')) as q_end
    ->   from (
    -> select 20211 as yrq union all
    -> select 20212 as yrq union all
    -> select 20213 as yrq union all
    -> select 20214 as yrq
    ->        ) x
    ->        ) y
    ->        ) z;
+------------+------------+
| q_start    | q_end      |
+------------+------------+
| 2021-01-01 | 2021-03-31 |
| 2021-04-01 | 2021-06-30 |
| 2021-07-01 | 2021-09-30 |
| 2021-10-01 | 2021-12-31 |
+------------+------------+
4 rows in set (0.00 sec)

mysql>

9.10 填充丢失的日期

需求:
为给定范围内的每个日期(每个月、周或年)生成一行信息。这样的行集通常用于生成综合报告。

例如,计算没年内每个月聘用的员工数。

解决方案:
这里的敲门是为每个月返回一行信息,即使并未聘用任何员工(此时该数为0)。
由于1980年1987年间并不是每个月都聘用过员工,因此必须生成这些月份,然后把按HIREDATE(聘用日期)与表EMP进行外连接(对HIREDATE截取月份,以便它能与生成的月份相匹配)。

sql
with recursive c(n) as
(
select 1 as n
union all
select n + 1 from c
 where n < 400
),
tmp1 as
(
select min(hiredate) min_hiredate,max(hiredate) max_hiredate
  from emp
),
tmp2 as
(
select min_hiredate,
       adddate(min_hiredate,-dayofyear(min_hiredate) + 1) new_min_hiredate,
       max_hiredate,
       date_add(adddate(max_hiredate,-dayofyear(max_hiredate) + 1),interval 12 month) new_max_hiredate
  from tmp1
),
tmp3 as
(
select date_add(new_min_hiredate, interval c.n - 1 month)  new_min_hiredate2
  from tmp2
inner join c
where date_add(new_min_hiredate, interval c.n - 1 month) < new_max_hiredate
)
select date_format(new_min_hiredate2,'%Y-%m') hired_mth,
       count(e.hiredate) as hired_nums
  from tmp3
 left join emp e
 on date_format(new_min_hiredate2,'%Y-%m') = date_format(e.hiredate,'%Y-%m')
 group by date_format(new_min_hiredate2,'%Y-%m')
 order by date_format(new_min_hiredate2,'%Y-%m')

测试记录:

sql
mysql> with recursive c(n) as
    -> (
    -> select 1 as n
    -> union all
    -> select n + 1 from c
    ->  where n < 400
    -> ),
    -> tmp1 as
    -> (
    -> select min(hiredate) min_hiredate,max(hiredate) max_hiredate
    ->   from emp
    -> ),
    -> tmp2 as
    -> (
    -> select min_hiredate,
    ->        adddate(min_hiredate,-dayofyear(min_hiredate) + 1) new_min_hiredate,
    ->        max_hiredate,
    ->        date_add(adddate(max_hiredate,-dayofyear(max_hiredate) + 1),interval 12 month) new_max_hiredate
    ->   from tmp1
    -> ),
    -> tmp3 as
    -> (
    -> select date_add(new_min_hiredate, interval c.n - 1 month)  new_min_hiredate2
    ->   from tmp2
    -> inner join c
    -> where date_add(new_min_hiredate, interval c.n - 1 month) < new_max_hiredate
    -> )
    -> select date_format(new_min_hiredate2,'%Y-%m') hired_mth,
    ->        count(e.hiredate) as hired_nums
    ->   from tmp3
    ->  left join emp e
    ->  on date_format(new_min_hiredate2,'%Y-%m') = date_format(e.hiredate,'%Y-%m')
    ->  group by date_format(new_min_hiredate2,'%Y-%m')
    ->  order by date_format(new_min_hiredate2,'%Y-%m');
+-----------+------------+
| hired_mth | hired_nums |
+-----------+------------+
| 1980-01   |          0 |
| 1980-02   |          0 |
| 1980-03   |          0 |
| 1980-04   |          0 |
| 1980-05   |          0 |
| 1980-06   |          0 |
| 1980-07   |          0 |
| 1980-08   |          0 |
| 1980-09   |          0 |
| 1980-10   |          0 |
| 1980-11   |          0 |
| 1980-12   |          1 |
| 1981-01   |          0 |
| 1981-02   |          2 |
| 1981-03   |          0 |
| 1981-04   |          1 |
| 1981-05   |          1 |
| 1981-06   |          1 |
| 1981-07   |          0 |
| 1981-08   |          0 |
| 1981-09   |          2 |
| 1981-10   |          0 |
| 1981-11   |          1 |
| 1981-12   |          2 |
| 1982-01   |          1 |
| 1982-02   |          0 |
| 1982-03   |          0 |
| 1982-04   |          0 |
| 1982-05   |          0 |
| 1982-06   |          0 |
| 1982-07   |          0 |
| 1982-08   |          0 |
| 1982-09   |          0 |
| 1982-10   |          0 |
| 1982-11   |          0 |
| 1982-12   |          0 |
| 1983-01   |          0 |
| 1983-02   |          0 |
| 1983-03   |          0 |
| 1983-04   |          0 |
| 1983-05   |          0 |
| 1983-06   |          0 |
| 1983-07   |          0 |
| 1983-08   |          0 |
| 1983-09   |          0 |
| 1983-10   |          0 |
| 1983-11   |          0 |
| 1983-12   |          0 |
| 1984-01   |          0 |
| 1984-02   |          0 |
| 1984-03   |          0 |
| 1984-04   |          0 |
| 1984-05   |          0 |
| 1984-06   |          0 |
| 1984-07   |          0 |
| 1984-08   |          0 |
| 1984-09   |          0 |
| 1984-10   |          0 |
| 1984-11   |          0 |
| 1984-12   |          0 |
| 1985-01   |          0 |
| 1985-02   |          0 |
| 1985-03   |          0 |
| 1985-04   |          0 |
| 1985-05   |          0 |
| 1985-06   |          0 |
| 1985-07   |          0 |
| 1985-08   |          0 |
| 1985-09   |          0 |
| 1985-10   |          0 |
| 1985-11   |          0 |
| 1985-12   |          0 |
| 1986-01   |          0 |
| 1986-02   |          0 |
| 1986-03   |          0 |
| 1986-04   |          0 |
| 1986-05   |          0 |
| 1986-06   |          0 |
| 1986-07   |          0 |
| 1986-08   |          0 |
| 1986-09   |          0 |
| 1986-10   |          0 |
| 1986-11   |          0 |
| 1986-12   |          0 |
| 1987-01   |          0 |
| 1987-02   |          0 |
| 1987-03   |          0 |
| 1987-04   |          0 |
| 1987-05   |          0 |
| 1987-06   |          2 |
| 1987-07   |          0 |
| 1987-08   |          0 |
| 1987-09   |          0 |
| 1987-10   |          0 |
| 1987-11   |          0 |
| 1987-12   |          0 |
+-----------+------------+
96 rows in set (0.00 sec)

mysql>

9.11 按照给定的时间单位进行查找

需求:
查找与给定月份、星期几或其它时间单位相匹配的日期。
例如,找到2月份和12月份聘用的所有员工,或者查找星期二聘用的所有员工。

解决方案:
用MySQL自带的函数即可。

sql
select ename
  from emp
 where month(hiredate) in (2,12) or weekday(hiredate) = 1;

测试记录:

sql
mysql> select ename
    ->   from emp
    ->  where month(hiredate) in (2,12) or weekday(hiredate) = 1;
+--------+
| ename  |
+--------+
| SMITH  |
| ALLEN  |
| WARD   |
| CLARK  |
| KING   |
| TURNER |
| JAMES  |
| FORD   |
+--------+
8 rows in set (0.00 sec)

9.12 使用日期的特殊部分比较记录

需求:
查找聘用日期月份和周内日期都相同的员工。

例如,如果在1983年3月10日星期一聘用了某个员工,而在2001年3月2日星期一聘用了另一个员工,那么二者的聘用日都在星期一,而且月份名一致,则可以认为他们相匹配。

解决方案:
因为要把一个员工的hiredate与另一个员工的hiredate相比较,所以需要对表emp进行自连接,这样,就可以对hiredate的每种组合进行比较,然后从每个hiredate中提取它是星期几及月份名,并进行比较。

sql
select concat(e1.ename,' was hired on the same month and weekday as ',e2.ename) as str
  from emp e1
 inner join emp e2
 on month(e1.hiredate) = month(e2.hiredate)
and weekday(e1.hiredate) = weekday(e2.hiredate)
and e1.empno <  e2.empno

测试记录:

sql
mysql> select concat(e1.ename,' was hired on the same month and weekday as ',e2.ename) as str
    ->   from emp e1
    ->  inner join emp e2
    ->  on month(e1.hiredate) = month(e2.hiredate)
    -> and weekday(e1.hiredate) = weekday(e2.hiredate)
    -> and e1.empno <  e2.empno;
+--------------------------------------------------------+
| str                                                    |
+--------------------------------------------------------+
| SCOTT was hired on the same month and weekday as ADAMS |
| JAMES was hired on the same month and weekday as FORD  |
+--------------------------------------------------------+
2 rows in set (0.00 sec)

9.13 识别重叠的日期范围

sql

create table emp_project(empno int, ename varchar(20), proj_id int, proj_start date, proj_end date);

insert into emp_project values (7782,'CLARK',1,'2005-06-16','2005-06-18');
insert into emp_project values (7782,'CLARK',4,'2005-06-19','2005-06-24');
insert into emp_project values (7782,'CLARK',7,'2005-06-22','2005-06-25');
insert into emp_project values (7782,'CALRK',10,'2005-06-25','2005-06-28');
insert into emp_project values (7782,'CLARK',13,'2005-06-28','2005-07-02');
insert into emp_project values (7839,'KING',2,'2005-06-17','2005-06-21');
insert into emp_project values (7839,'KING',8,'2005-06-23','2005-06-25');
insert into emp_project values (7839,'KING',14,'2005-06-29','2005-06-30');
insert into emp_project values (7839,'KING',11,'2005-06-26','2005-06-27');
insert into emp_project values (7839,'KING',5,'2005-06-20','2005-06-24');
insert into emp_project values (7934,'MILLER',3,'2005-06-18','2005-06-22');
insert into emp_project values (7934,'MILLER',12,'2005-06-27','2005-06-28');
insert into emp_project values (7934,'MILLER',15,'2005-06-30','2005-07-03');
insert into emp_project values (7934,'MILLER',9,'2005-06-24','2005-06-27');
insert into emp_project values (7934,'MILLER',6,'2005-06-21','2005-06-23');

需求:
查找员工在老工程结束之前就开始新工程的所有实例。

观察一下员工KING的结果,会浮现KING在完成PROJ_ID 5之前开始了PROJ_ID 8,而且在完成PROJ_ID之前又开始了PROJ_ID5.

解决方案:
这里的关键是,找打PROJ_START(新工程的开始日期)出现另一个工程的PROJ_START之后PROJ_END日期之前的那些行。
首先,应该把同一个员工的每个工程与另一个工程相比较。
对EMP_PROJECT按员工进行自连接,得到每个员工任意两个工程的所有组合。
要找到重叠的情况,只需找到一个PROJ_ID的PROJ_START介于另一个PROJ_ID的PROJ_START和PROJ_END之间的所有行即可。

sql
select a.empno, a.ename,
       concat('project ',b.proj_id,
               ' overlaps project ',a.proj_id) as msg
  from emp_project a,
       emp_project b
 where a.empno = b.empno
   and b.proj_start >= a.proj_start
   and b.proj_start <= a.proj_end
   and a.proj_id != b.proj_id;

测试记录:

sql
mysql> select a.empno, a.ename,
    ->        concat('project ',b.proj_id,
    ->                ' overlaps project ',a.proj_id) as msg
    ->   from emp_project a,
    ->        emp_project b
    ->  where a.empno = b.empno
    ->    and b.proj_start >= a.proj_start
    ->    and b.proj_start <= a.proj_end
    ->    and a.proj_id != b.proj_id;
+-------+--------+--------------------------------+
| empno | ename  | msg                            |
+-------+--------+--------------------------------+
|  7782 | CLARK  | project 7 overlaps project 4   |
|  7782 | CLARK  | project 10 overlaps project 7  |
|  7782 | CALRK  | project 13 overlaps project 10 |
|  7839 | KING   | project 8 overlaps project 5   |
|  7839 | KING   | project 5 overlaps project 2   |
|  7934 | MILLER | project 12 overlaps project 9  |
|  7934 | MILLER | project 6 overlaps project 3   |
+-------+--------+--------------------------------+
7 rows in set (0.00 sec)

mysql>

十.范围处理

10.1 定位连续值范围

定位连续值范围

10.2 查找同一组或分区中行之前的差

查找同一组或分区中行的差

10.3 定义连续值范围的开始和结束点

定义连续值范围的开始点和结束点

10.4 补充范围内丢失的值

问题:
返回1980年起始的十年间每年聘用的员工数,但有些奶粉并没有聘用员工。

解决方案:
这个解决方案的技巧是,对为聘用任何员工的年份返回0。

sql
with recursive c(n) as
(
select 1 as n
union all
select n + 1 from c where n < 10
),
tmp1 as
(
select year(min(hiredate)) min_hiredate
  from emp
),
tmp2 as
(
select min_hiredate + n as new_hired
  from tmp1
 inner join c
 )
 select new_hired,
        count(emp.hiredate)
   from tmp2
 left join emp 
   on tmp2.new_hired = year(hiredate)
 group by new_hired
 order by new_hired

测试记录:

sql
mysql> with recursive c(n) as
    -> (
    -> select 1 as n
    -> union all
    -> select n + 1 from c where n < 10
    -> ),
    -> tmp1 as
    -> (
    -> select year(min(hiredate)) min_hiredate
    ->   from emp
    -> ),
    -> tmp2 as
    -> (
    -> select min_hiredate + n as new_hired
    ->   from tmp1
    ->  inner join c
    ->  )
    ->  select new_hired,
    ->         count(emp.hiredate)
    ->    from tmp2
    ->  left join emp
    ->    on tmp2.new_hired = year(hiredate)
    ->  group by new_hired
    ->  order by new_hired;
+-----------+---------------------+
| new_hired | count(emp.hiredate) |
+-----------+---------------------+
|      1981 |                  10 |
|      1982 |                   1 |
|      1983 |                   0 |
|      1984 |                   0 |
|      1985 |                   0 |
|      1986 |                   0 |
|      1987 |                   2 |
|      1988 |                   0 |
|      1989 |                   0 |
|      1990 |                   0 |
+-----------+---------------------+
10 rows in set (0.00 sec)

10.5 生成连续数字

生成连续数字

十一.高级查找

11.1 给结果集分页

按结果集分页

11.2 跳过表中的n行

跳过表中的n行

11.3 在外连接中用OR逻辑

在外连接中用 or 逻辑

11.4 确定哪些行是彼此互换的

确定那些行是彼此互换的

11.5 选择前n个记录

选择前n个记录

11.6 找到包含最大值和最小值的记录

找到包含最大值和最小值的记录

11.7 存取"未来"行

存取“未来”行

11.8 轮换行值

轮换行值

11.9 给结果集分等级

给结果集分等级

11.10 抑制重复

抑制重复

11.11 找到骑士值

找到骑士值

11.12 生成简单的预测

生成简单的预测

十二.报表和数据仓库运算

12.1 将结果集转为一行

将结果集转置为一行

12.2 把结果集转置为多行

把结果集转置为多行

12.3 反向转置结果集

反向转置结果集

12.4 将结果集反向转置为一列

将结果集反向转为一列

12.5 抑制结果集中的重复值

抑制结果集中的重复值

12.6 转置结果集以利于跨行计算

转置结果集以利于跨行计算

12.7 创建固定大小的数据桶

创建固定大小的桶

12.8 创建预定数目的桶

创建预定数目的桶

12.9 创建横向直方图

创建横向直方图

12.10 创建纵向直方图

创建纵向直方图

12.11 返回未包含在group by中的列

返回未包含在group by中的列

12.12 计算简单的小计

计算简单的小计

12.13 计算所有表达式组合的小计

计算所有表达式组合的小计

12.14 判别非小计的行

分组语句

根据grouping来判断是否是小计的行

12.15 使用case表达式给行做标记

使用CASE表达式给行做标记

12.16 创建稀疏矩阵

需求:
创建一个稀疏的矩阵。

例如这个sql:

sql
select  case deptno when 10 then ename end as d10,
        case deptno when 20 then ename end as d20,
        case deptno when 30 then ename end as d30,
        case job when 'CLERK' then ename end as clerks,
        case job when 'MANAGER' then ename end as mgrs,
        case job when 'PRESIDENT' then ename end as prez,
        case job when 'ALALYST' then ename end as anals,
        case job when 'SALESMAN' then ename end as sales
  from  emp;

生成了一个稀疏的矩阵

解决方案:
把deptno和job行变换为列,只需使用case表达式,判断由这些行返回的可能性。这就是对它的所有解释。
另外,如果想使报表变'稠密',并去除一些null行,就需要找到分组的依据。

例如,使用串口函数row_number over,为每个deptno中的每个员工分等级,然后使用聚集函数max去掉一些null

sql
mysql> select  case deptno when 10 then ename end as d10,
    ->         case deptno when 20 then ename end as d20,
    ->         case deptno when 30 then ename end as d30,
    ->         case job when 'CLERK' then ename end as clerks,
    ->         case job when 'MANAGER' then ename end as mgrs,
    ->         case job when 'PRESIDENT' then ename end as prez,
    ->         case job when 'ALALYST' then ename end as anals,
    ->         case job when 'SALESMAN' then ename end as sales
    ->   from  emp;
+--------+-------+--------+--------+-------+------+-------+--------+
| d10    | d20   | d30    | clerks | mgrs  | prez | anals | sales  |
+--------+-------+--------+--------+-------+------+-------+--------+
| NULL   | SMITH | NULL   | SMITH  | NULL  | NULL | NULL  | NULL   |
| NULL   | NULL  | ALLEN  | NULL   | NULL  | NULL | NULL  | ALLEN  |
| NULL   | NULL  | WARD   | NULL   | NULL  | NULL | NULL  | WARD   |
| NULL   | JONES | NULL   | NULL   | JONES | NULL | NULL  | NULL   |
| NULL   | NULL  | MARTIN | NULL   | NULL  | NULL | NULL  | MARTIN |
| NULL   | NULL  | BLAKE  | NULL   | BLAKE | NULL | NULL  | NULL   |
| CLARK  | NULL  | NULL   | NULL   | CLARK | NULL | NULL  | NULL   |
| NULL   | SCOTT | NULL   | NULL   | NULL  | NULL | NULL  | NULL   |
| KING   | NULL  | NULL   | NULL   | NULL  | KING | NULL  | NULL   |
| NULL   | NULL  | TURNER | NULL   | NULL  | NULL | NULL  | TURNER |
| NULL   | ADAMS | NULL   | ADAMS  | NULL  | NULL | NULL  | NULL   |
| NULL   | NULL  | JAMES  | JAMES  | NULL  | NULL | NULL  | NULL   |
| NULL   | FORD  | NULL   | NULL   | NULL  | NULL | NULL  | NULL   |
| MILLER | NULL  | NULL   | MILLER | NULL  | NULL | NULL  | NULL   |
+--------+-------+--------+--------+-------+------+-------+--------+
14 rows in set (0.00 sec)

解决方案:

sql
select  max(case deptno when 10 then ename end) as d10,
        max(case deptno when 20 then ename end) as d20,
        max(case deptno when 30 then ename end) as d30,
        max(case job when 'CLERK' then ename end) as clerks,
        max(case job when 'MANAGER' then ename end) as mgrs,
        max(case job when 'PRESIDENT' then ename end) as prez,
        max(case job when 'ANALYST' then ename end) as anals,
        max(case job when 'SALESMAN' then ename end) as sales
  from  ( 
  select deptno, job, ename,
         row_number() over (partition by deptno order by empno) rn
    from emp
   ) x
 group by rn
  ;

12.17 按时间按单位给行分组

按时间单位进行分组

12.18 对不同组/分区同时实现聚集

对不同组/分区进行聚集

12.19 对移动范围内的值进行聚集

对移动范围内的值进行聚集

12.20 转置带小计的结果集

转置带小计的结果集

十三.分层查询

13.1 表示父子关系

表示 父-子关系

13.2 表示父-子-祖关系

表示 子-父-祖父关系

13.3 创建表的分层视图

创建表的分层视图

13.4 为给定父行找到所有子行

为给定父行找到所有子行

13.5 确定哪些是叶节点、分支节点及根节点

确定哪些是叶节点、分子节点、根节点

十四.若干另类目标

14.4 从不固定位置提取字符串元素

从不固定位置提取字符串元素

14.8 转置已分等级的结果集

转置已分等级的结果集

14.9 给两次转置的结果集增加列头

给两次转置的结果集增加列头

经纬度点到点距离公式

  1. 需求:判断点(经纬度)是否在半径内
  2. 难点:如何求取点在不规则的范围内

公式:(米)

text
sqrt(power(6371393*abs(a.lat-b.lat)*3.14159265/180,2)+power(6371393*abs(a.lon-b.lon)*3.14159265/180*cos(a.lat*3.14159265/180),2))

需要补充其他写法与补充事项

练习题 1

11.游戏玩法分析1

text
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
text
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-05-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |

每行数据记录了一名玩家在退出平台之前,当天使用同一台设备登录平台后打开的游戏的数目(可能是 0 个),写一条 SQL 查询语句获取每位玩家 第一次登陆平台的日期。

sql
-- 我的mysql答案
select
player_id,
min(event_date) as first_login 
from
Activity t
group  by   player_id
order by player_id 
sql
-- 注意Oracle中的to_char函数
SELECT player_id, MIN(to_char(event_date, 'yyyy-MM-dd')) AS first_login
FROM Activity
GROUP BY player_id

考虑不确定的情况

sql
select
	player_id,
	to_char(event_date, 'yyyy-mm-dd') as first_login
from
	(select
		player_id,
		event_date,
		row_number() over (partition by player_id order by event_date asc) rn
	from Activity)
where rn = 1

12.游戏玩法分析二(row_number() 和dense_rank() 的效率)

请编写一个 SQL 查询,描述每一个玩家首次登陆的设备名称

sql
-- 我的Oracle答案
with x as (
select
player_id , device_id,
row_number() over(partition by player_id order by event_date) as rn
from
Activity t
) 
select
x.player_id,x.device_id
from 
x
where x.rn =1
sql
-- 使用子查询
select player_id, device_id
from Activity
where (player_id, event_date) in (select player_id, min(event_date)
                                  from Activity
                                  group by player_id);
错误的写法:子查询的id没有作用到父查询中
sql
select
    player_id, device_id
from 
    Activity
where 
    event_date in 
    (
        select min(event_date) as event_date
        from Activity
        group by player_id
    )

13.游戏玩法分析三(sum窗口函数自连接的实现)

编写一个 SQL 查询,同时报告每组玩家和日期,以及玩家到目前为止玩了多少游戏。也就是说,在此日期之前玩家所玩的游戏总数。详细情况请查看示例

Activity table:

text
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-05-02 | 6            |
| 1         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result table:

text
+-----------+------------+---------------------+
| player_id | event_date | games_played_so_far |
+-----------+------------+---------------------+
| 1         | 2016-03-01 | 5                   |
| 1         | 2016-05-02 | 11                  |
| 1         | 2017-06-25 | 12                  |
| 3         | 2016-03-02 | 0                   |
| 3         | 2018-07-03 | 5                   |
+-----------+------------+---------------------+

对于 ID 为 1 的玩家,2016-05-02 共玩了 5+6=11 个游戏,2017-06-25 共玩了 5+6+1=12 个游戏。
对于 ID 为 3 的玩家,2018-07-03 共玩了 0+5=5 个游戏。
请注意,对于每个玩家,我们只关心玩家的登录日期

sql
-- 我的窗口写法
select 
player_id,to_char(event_date,'yyyy-mm-dd') as event_date,
sum(games_played) over(partition by player_id order by event_date ) as games_played_so_far
from
Activity
sql
--自连接
SELECT
	a.player_id,
	a.event_date,
	SUM(b.games_played) AS games_played_so_far
FROM
	Activity AS a
	INNER JOIN Activity AS b
	ON a.player_id = b.player_id AND b.event_date <= a.event_date
GROUP BY
	a.player_id, 
	a.event_date

image.png

14.游戏的玩法四

编写一个 SQL 查询,报告在首次登录的第二天再次登录的玩家的比率,四舍五入到小数点后两位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数

反思看错题目了,题目只是说首次登录的第二天是否登录了,我使用的是lag函数开窗解决的,然后去重,事实上只要求最小的登录时间即可.....

sql
-- 我的写法2
select 
round((count(b.player_id) / count(a.player_id) ),2) as   fraction 
from 
(
select 
player_id,min(event_date) as event_date
from
Activity
group by player_id
) a 
left join Activity b 
on a.player_id = b.player_id and datediff(b.event_date,a.event_date) =1
sql
-- 使用avg也可
select round(avg(a.event_date is not null), 2) fraction
from 
    (select player_id, min(event_date) as login
    from activity
    group by player_id) p 
left join activity a 
on p.player_id=a.player_id and datediff(a.event_date, p.login)=1

15.中位数

text
+-----+------------+--------+
|Id   | Company    | Salary |
+-----+------------+--------+
|1    | A          | 2341   |
|2    | A          | 341    |
|3    | A          | 15     |
|4    | A          | 15314  |
|5    | A          | 451    |
|6    | A          | 513    |
|7    | B          | 15     |
|8    | B          | 13     |
|9    | B          | 1154   |
|10   | B          | 1345   |
|11   | B          | 1221   |
|12   | B          | 234    |
|13   | C          | 2345   |
|14   | C          | 2645   |
|15   | C          | 2645   |
|16   | C          | 2652   |
|17   | C          | 65     |
+-----+------------+--------+

请编写SQL查询来查找每个公司的薪水中位数

sql
select Id,Company,Salary
from
(
select Id,Company,Salary, 
row_number()over(partition by Company order by Salary)as ranking,
count(Id) over(partition by Company)as cnt
from Employee
)a
where ranking>=cnt/2 and ranking<=cnt/2+1

使用两个序列函数,发现问题,用spark检验一下,问题出在C是单数

text
+---+-------+------+------+-------+
|Id |Company|Salary|asc_rn|desc_rn|
+---+-------+------+------+-------+
|12 |B      |234   |6     |1      |
|7  |B      |15    |5     |2      |
|10 |B      |1345  |4     |3      |
|8  |B      |13    |3     |4      |
|11 |B      |1221  |2     |5      |
|9  |B      |1154  |1     |6      |
|17 |C      |65    |5     |1      |
|16 |C      |2652  |4     |2      |
|14 |C      |2645  |2     |3      |
|15 |C      |2645  |3     |4      |
|13 |C      |2345  |1     |5      |
|6  |A      |513   |6     |1      |
|5  |A      |451   |5     |2      |
|2  |A      |341   |4     |3      |
|1  |A      |2341  |3     |4      |
|4  |A      |15314 |2     |5      |
|3  |A      |15    |1     |6      |
+---+-------+------+------+-------+

正确的写法是添加ID字段的排序,由于薪资的在题目中是重复的使用两个序列函数只比较一个字段的化,会乱序,因为一个字段值相同就会比较下一个字段,而默认的比较方法是降序的

sql
with x as(
select 
Id,Company,Salary,
row_number() over(partition by Company order by Salary asc ,Id asc ) as asc_rn,
row_number() over(partition by Company order by Salary desc ,Id desc) as desc_rn,
count(1) over(partition by Company ) as  cnt 
from
Employee e
)
select 
Id,Company,Salary
from 
x
where (mod(cnt,2) = 1 and asc_rn = desc_rn ) or (mod(cnt,2)=0 and abs(asc_rn-desc_rn) =1)

这道题目还未完成还有补充的空间:例如使用自连接怎么优化它

16.至少有5名直接下属的经理

text
Employee 表包含所有员工和他们的经理。每个员工都有一个 Id,并且还有一列是经理的 Id。
+------+----------+-----------+----------+
|Id    |Name 	  |Department |ManagerId |
+------+----------+-----------+----------+
|101   |John 	  |A 	      |null      |
|102   |Dan 	  |A 	      |101       |
|103   |James 	  |A 	      |101       |
|104   |Amy 	  |A 	      |101       |
|105   |Anne 	  |A 	      |101       |
|106   |Ron 	  |B 	      |101       |
+------+----------+-----------+----------+

给定 Employee 表,请编写一个SQL查询来查找至少有5名直接下属的经理。对于上表,您的SQL查询应该返回:

text
+-------+
| Name  |
+-------+
| John  |
+-------+
sql
-- 我的写法,我习惯使用with,在大数据领域with 不一定全部在内存中可配置参数到磁盘
with x as (
select
e1.Name as Employee_name ,e2.Name as Manager_name
from
Employee e1
join Employee e2
on e1.ManagerId = e2.Id
)
select 
Manager_name as Name
from 
x
group by Manager_name
having count(1) >=5

其他解法,类似可以我的解法,一步完成,这道题目的坑在于null的处理使用join内连接

17.给定数字的频率查询中位数(两个序列函数)

text
Numbers 表保存数字的值及其频率。
+----------+-------------+
|  Number  |  Frequency  |
+----------+-------------|
|  0       |  7          |
|  1       |  1          |
|  2       |  3          |
|  3       |  1          |
+----------+-------------+
text
在此表中,数字为 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3,所以中位数是 (0 + 0) / 2 = 0
+--------+
| median |
+--------|
| 0.0000 |
+--------+
sql
--我的解法,还是上面的方法中位数的两个序列函数排序思想
select avg(number) as median
from
(select Number, frequency,
        sum(frequency) over(order by number asc) as total,
        sum(frequency) over(order by number desc) as total1
from Numbers
order by number asc)as a
where total>=(select sum(frequency) from Numbers)/2
and total1>=(select sum(frequency) from Numbers)/2
sql
select
    avg(n.Number) as median
from
    Numbers as n
where
    n.Frequency >= abs(
        (select sum(Frequency) from Numbers where Number <= n.Number) - 
        (select sum(Frequency) from Numbers where Number >= n.Number)
    )
sql
-- 理解起来有点难度...
SELECT 
AVG(Number)median 
FROM
(SELECT n1.Number FROM Numbers n1 JOIN Numbers n2 ON n1.Number>=n2.Number 
 GROUP BY 
 n1.Number 
 HAVING 
 SUM(n2.Frequency)>=(SELECT SUM(Frequency) FROM Numbers)/2 
 AND 
 SUM(n2.Frequency)-AVG(n1.Frequency)<=(SELECT SUM(Frequency) FROM Numbers)/2
)s

18.当选者

text
+-----+---------+
| id  | Name    |
+-----+---------+
| 1   | A       |
| 2   | B       |
| 3   | C       |
| 4   | D       |
| 5   | E       |
+-----+---------+  
text
+-----+--------------+
| id  | CandidateId  |
+-----+--------------+
| 1   |     2        |
| 2   |     4        |
| 3   |     3        |
| 4   |     2        |
| 5   |     5        |
+-----+--------------+
id 是自动递增的主键,
CandidateId 是 Candidate 表中的 id.

请编写 sql 语句来找到当选者的名字,上面的例子将返回当选者 B.

text
+------+
| Name |
+------+
| B    |
+------+
sql
--我的解答,我忘记用limit函数了.....我这个答案不知道哪里有问题,只好在写一个了...
with x as (
select 
CandidateId
from 
(
select 
CandidateId,row_number(order by num1 desc) as rn
from 
(
select 
CandidateId, count(1) as num1
from 
Vote
group CandidateId
) t1
) t2
where rn =1
)

select 
Name
from 
Candidate y
where y.id = x.CandidateId
sql
select name from Candidate where id =(
select CandidateId
from Vote
group by CandidateId 
order by count(*) desc
limit 1)

19.员工奖金

sql
select
name,bonus
from
Employee t
left join  Bonus t1
on t.empId  = t1.empId
where bonus <1000 or bonus is null

注意where条件后要加 is null 懒得写了,577题,简单题

20查询回答率最高的问题

从 survey_log 表中获得回答率最高的问题,survey_log 表包含这些列:id, action, question_id, answer_id, q_num, timestamp。
id 表示用户 id;action 有以下几种值:"show","answer","skip";当 action 值为 "answer" 时 answer_id 非空,而 action 值为 "show" 或者 "skip" 时 answer_id 为空;q_num 表示当前会话中问题的编号。
请编写 SQL 查询来找到具有最高回答率的问题。
回答率最高的含义是:同一问题编号中回答数占显示数的比例最高

输入:

text
+------+-----------+--------------+------------+-----------+------------+
| id   | action    | question_id  | answer_id  | q_num     | timestamp  |
+------+-----------+--------------+------------+-----------+------------+
| 5    | show      | 285          | null       | 1         | 123        |
| 5    | answer    | 285          | 124124     | 1         | 124        |
| 5    | show      | 369          | null       | 2         | 125        |
| 5    | skip      | 369          | null       | 2         | 126        |
+------+-----------+--------------+------------+-----------+------------+

输出:

text
+-------------+
| survey_log  |
+-------------+
|    285      |
+-------------+

解释:
问题 285 的回答率为 1/1,而问题 369 回答率为 0/1,因此输出 285 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/get-highest-answer-rate-question
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

sql
-- 我的答案
select question_id as survey_log
from survey_log
group by question_id
order by sum(if(action = 'answer', 1, 0)) / sum(if(action = 'show', 1, 0)) desc
limit 1
sql
select question_id as survey_log
from (
  select
      question_id,
      sum(if(action = 'answer', 1, 0)) as AnswerCnt,
      sum(if(action = 'show', 1, 0)) as ShowCnt
  from
      survey_log
  group by question_id
) as tbl
order by (AnswerCnt / ShowCnt) desc
limit 1

题目的意思不是很明确,主要考察sum和if结合使用,简单题

练习题 2

21.查询员工的累计薪水(☆)

Employee 表保存了一年内的薪水信息。
请你编写 SQL 语句,对于每个员工,查询他除最近一个月(即最大月)之外,剩下每个月的近三个月的累计薪水(不足三个月也要计算)。
结果请按 Id 升序,然后按 Month 降序显示

text
| Id | Month | Salary |
|----|-------|--------|
| 1  | 1     | 20     |
| 2  | 1     | 20     |
| 1  | 2     | 30     |
| 2  | 2     | 30     |
| 3  | 2     | 40     |
| 1  | 3     | 40     |
| 3  | 3     | 60     |
| 1  | 4     | 60     |
| 3  | 4     | 70     |

-- 输出
| Id | Month | Salary |
|----|-------|--------|
| 1  | 3     | 90     |
| 1  | 2     | 50     |
| 1  | 1     | 20     |
| 2  | 1     | 20     |
| 3  | 3     | 100    |
| 3  | 2     | 40     |
sql
-- lag与窗口的大小
-- 理解求每个月最近三个月 rows between 2 preceding and current row
select 
Id,Month,
sum(Salary) over(partition by Id order by Month rows between 2 preceding and current row ) Salary
from 
(
select
Id,Month,Salary,
lag(Salary,1,0) over(partition by Id order by Month desc) rn 
from
Employee
) 
where rn != 0
order by Id,Month desc
sql
-- 这也可以非常好的方法,使用两个偏移量函数,求总和,使用一个序列函数来过滤出最大月份的情况,不用窗口就是自连接也可以写
SELECT ID, MONTH, SALARY + IFNULL(L1, 0) + IFNULL(L2, 0) AS SALARY
FROM (SELECT *, LAG(SALARY, 1) OVER(PARTITION BY ID ORDER BY MONTH) AS L1, LAG(SALARY, 2) OVER(PARTITION BY ID ORDER BY MONTH) AS L2, RANK() OVER(PARTITION BY ID ORDER BY MONTH DESC) AS `RANK`
      FROM EMPLOYEE) AS A
WHERE `RANK` > 1
ORDER BY 1, 2 DESC;

22.统计各个专业学生数

一所大学有 2 个数据表,分别是 student 和 department ,这两个表保存着每个专业的学生数据和院系数据。
写一个查询语句,查询 department 表中每个专业的学生人数 (即使没有学生的专业也需列出)。
将你的查询结果按照学生人数降序排列。 如果有两个或两个以上专业有相同的学生数目,将这些部门按照部门名字的字典序从小到大排列

text
student 表格如下:

| Column Name  | Type      |
|--------------|-----------|
| student_id   | Integer   |
| student_name | String    |
| gender       | Character |
| dept_id      | Integer   |
其中, student_id 是学生的学号, student_name 是学生的姓名, gender 是学生的性别, dept_id 是学生所属专业的专业编号。

department 表格如下:

| Column Name | Type    |
|-------------|---------|
| dept_id     | Integer |
| dept_name   | String  |
sql
-- 考察的就是count(*) count(表达式) 为null的处理
select 
dept_name,
count(student_name) as student_number
from
(
select 
dept_name,student_name
from 
department 
left join 
student
on department.dept_id = student.dept_id
) t
group by dept_name
order by student_number desc ,dept_name

23.推荐人

给定表 customer ,里面保存了所有客户信息和他们的推荐人。

text
+------+------+-----------+
| id   | name | referee_id|
+------+------+-----------+
|    1 | Will |      NULL |
|    2 | Jane |      NULL |
|    3 | Alex |         2 |
|    4 | Bill |      NULL |
|    5 | Zack |         1 |
|    6 | Mark |         2 |
+------+------+-----------+

写一个查询语句,返回一个编号列表,列表中编号的推荐人的编号都 不是 2。

简单题,但是是我的知识的盲区了,官方的答案

MySQL 使用三值逻辑 —— TRUE, FALSE 和 UNKNOWN。任何与 NULL 值进行的比较都会与第三种值 UNKNOWN 做比较。这个“任何值”包括 NULL 本身!这就是为什么 MySQL 提供 IS NULL 和 IS NOT NULL 两种操作来对 NULL 特殊判断。
因此,在 WHERE 语句中我们需要做一个额外的条件判断 `referee_id IS NULL'。

避免错误的秘诀在于使用 IS NULL 或者 IS NOT NULL 两种操作来对 NULL 值做特殊判断
SELECT name FROM customer WHERE referee_id = NULL OR referee_id <> 2;

sql
-- 这样写法的执行的速度大于用 != 2,为什么???
select name
from customer
where referee_id < 2 or referee_id > 2 or referee_id is null

24.2016年的投资(窗口写法)

写一个查询语句,将 2016 年 (TIV_2016) 所有成功投资的金额加起来,保留 2 位小数
对于一个投保人,他在 2016 年成功投资的条件是:
他在 2015 年的投保额 (TIV_2015) 至少跟一个其他投保人在 2015 年的投保额相同。
他所在的城市必须与其他投保人都不同(也就是说维度和经度不能跟其他任何一个投保人完全相同)

输入格式:
表 insurance 格式如下:

text
| Column Name | Type          |
|-------------|---------------|
| PID         | INTEGER(11)   |
| TIV_2015    | NUMERIC(15,2) |
| TIV_2016    | NUMERIC(15,2) |
| LAT         | NUMERIC(5,2)  |
| LON         | NUMERIC(5,2)  |

PID 字段是投保人的投保编号, TIV_2015 是该投保人在2015年的总投保金额, TIV_2016 是该投保人在2016年的投保金额, LAT 是投保人所在城市的维度, LON 是投保人所在城市的经度。

样例输入

text
| PID | TIV_2015 | TIV_2016 | LAT | LON |
|-----|----------|----------|-----|-----|
| 1   | 10       | 5        | 10  | 10  |
| 2   | 20       | 20       | 20  | 20  |
| 3   | 10       | 30       | 20  | 20  |
| 4   | 10       | 40       | 40  | 40  |

样例输出

text
| TIV_2016 |
|----------|
| 45.00    |
sql
-- 我的写法使用concat函数
select 
round(sum(TIV_2016) , 2) as TIV_2016
from 
insurance
where TIV_2015 in 
(
select 
TIV_2015
from
insurance
group by TIV_2015
having count(TIV_2015) >1
)
and concat(lat, lon) in
(
select
concat(lat, lon)
from
insurance
group by lat , lon
having count(*) = 1
)
sql
-- 窗口写法
SELECT ROUND(SUM(TIV_2016), 2) AS TIV_2016
FROM (SELECT *, COUNT(*) OVER(PARTITION BY TIV_2015) AS C1, COUNT(*) OVER(PARTITION BY LAT, LON) AS C2
      FROM INSURANCE) AS A
WHERE C1 > 1
AND C2 = 1;

25.订单最多的客户

sql
-- 简单题,考虑如果并列第一的话使用where 1
select
customer_number
from
orders
group by customer_number
order by  count(1) desc 
limit 1

26.大的国家(union 和 or 哪个的效率高)

 https://stackoverflow.com/questions/13750475/sql-performance-union-vs-o

为了不影响性能,可以使用union all,然后手动排序去重

这里有张 World 表

text
+-----------------+------------+------------+--------------+---------------+
| name            | continent  | area       | population   | gdp           |
+-----------------+------------+------------+--------------+---------------+
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+-----------------+------------+------------+--------------+---------------+

如果一个国家的面积超过 300 万平方公里,或者人口超过 2500 万,那么这个国家就是大国家。

编写一个 SQL 查询,输出表中所有大国家的名称、人口和面积。

例如,根据上表,我们应该输出:

text
+--------------+-------------+--------------+
| name         | population  | area         |
+--------------+-------------+--------------+
| Afghanistan  | 25500100    | 652230       |
| Algeria      | 37100000    | 2381741      |
+--------------+-------------+--------------+
sql
SELECT
    name, population, area
FROM
    world
WHERE
    area > 3000000

UNION

SELECT
    name, population, area
FROM
    world
WHERE
    population > 25000000

27.超过5名学生的课

sql
-- 注意去重即可
select
class
from
courses
group by class
having count(DISTINCT student) >=5

28.好友申请1-总体通过率

sql
-- 注意ifnull的用法以及理解题意
select
round(
ifnull(
(select count(*) from (select distinct requester_id, accepter_id from RequestAccepted) as A)
/
(select count(*) from (select distinct sender_id, send_to_id from FriendRequest) as B),
0)
, 2) as accept_rate;

29.图书馆的人流量

编写一个 SQL 查询以找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。

表:Stadium

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| visit_date    | date    |
| people        | int     |
+---------------+---------+

visit_date 是表的主键
每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)
每天只有一行记录,日期随着 id 的增加而增加
 
返回按 visit_date 升序排列的结果表。

查询结果格式如下所示。

Stadium table:

text
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
| 1    | 2017-01-01 | 10        |
| 2    | 2017-01-02 | 109       |
| 3    | 2017-01-03 | 150       |
| 4    | 2017-01-04 | 99        |
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-09 | 188       |
+------+------------+-----------+

Result table:

text
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-09 | 188       |
+------+------------+-----------+

id 为 5、6、7、8 的四行 id 连续,并且每行都有 >= 100 的人数记录。
请注意,即使第 7 行和第 8 行的 visit_date 不是连续的,输出也应当包含第 8 行,因为我们只需要考虑 id 连续的记录。
不输出 id 为 2 和 3 的行,因为至少需要三条 id 连续的记录。

sql
-- 以前写过一遍 我在纠结select 和 having的执行顺序问题,怎么和hive的不一样嫩
//可直接子查询过滤出count(1) >3 的:where rk in (
//select rk from t1 group by rk having count(1) >= 3);
select 
id,
to_char(visit_date,'yyyy-mm-dd') as visit_date,
people
from 
(
select
id,
visit_date,
people,
count(1) over(partition by rn ) as rm1
from
(
select
id,
visit_date,
people,
(id - row_number() over(order by id)) as rn  
from
Stadium
where 
people >= 100
) t
) t1
where rm1 >=3
order by id 
sql
select distinct t2.*    
from(
    select *, 
    lead(people,1)over(order by visit_date  ) as p2,
    lead(people,2)over(order by visit_date ) as p3
    from Stadium 
)t, Stadium t2
where t.people >=100 and p2>=100 and p3>=100 and 
t2.id>=t.id and t2.id-2<=t.id

30.好友申请2-谁有最多的好友(注意union all 用法)

表 request_accepted 存储了所有好友申请通过的数据记录,其中, requester_id 和 accepter_id 都是用户的编号。

text
| requester_id | accepter_id | accept_date|
|--------------|-------------|------------|
| 1            | 2           | 2016_06-03 |
| 1            | 3           | 2016-06-08 |
| 2            | 3           | 2016-06-08 |
| 3            | 4           | 2016-06-09 |

写一个查询语句,求出谁拥有最多的好友和他拥有的好友数目。对于上面的样例数据,结果为:

text
| id | num |
|----|-----|
| 3  | 3   |

注意:

保证拥有最多好友数目的只有 1 个人。
好友申请只会被接受一次,所以不会有 requester_id 和 accepter_id 值都相同的重复记录。

sql
-- 开窗写不知道哪里错了,用spark检验一下,没检查出来重新了一遍,估计是符号错了
select
id,num
from
(
select 
id,sum(num) as num,
row_number(order by sum(num)  desc) as  rn
from 
(
select 
requester_id as id,
count(1) as num
from
request_accepted
group by requester_id
union all 
select 
accepter_id as id,
count(1) as num
from
request_accepted
group by accepter_id
) 
group by id
) t
where rn =1 
sql
-- 正确的写法
select
id,nu as num
from
(
select
id,sum(num) as nu,
row_number() over(order by sum(num) desc) as rn
from
(
select requester_id as id, count(1) as num from request_accepted group by requester_id
union all
select  accepter_id as id1, count(1) as num1 from request_accepted group by accepter_id
) t1
group by id
) t2
where rn =1
sql
-- 使用union all 连接
select id, count(*) num
from 
    (select requester_id id from request_accepted 
    union all
    select accepter_id id from request_accepted) tmp 
group by id
order by count(*) desc
limit 1;

练习题 3

31.连续空余座位

你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?

几个朋友来到电影院的售票处,准备预约连续空余座位。

text
| seat_id | free |
|---------|------|
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |

对于如上样例,你的查询语句应该返回如下结果。

text
| seat_id |
|---------|
| 3       |
| 4       |
| 5       |

注意:
seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。
连续空余座位的定义是大于等于 2 个连续空余的座位。

sql
--我的写法,可以考虑把row_number() 提取出来with 
select 
seat_id
from 
(
select
rn
from 
(
select 
seat_id,
(seat_id - row_number() over(order by seat_id) ) as rn
from 
cinema
where free =1
)
group by rn
having count(1) >1
) t
join 
(
select 
seat_id,
(seat_id - row_number() over(order by seat_id) ) as rn
from 
cinema
where free =1    
) t1
on t.rn = t1.rn
order by seat_id
sql
with sub as (
    select seat_id,seat_id - rank() over(order by seat_id) as rk from cinema
    where free = 1
)
select seat_id
from sub
where rk in (select rk from sub group by rk having count(1) > 1)
sql
-- 评论区提供了lag偏移函数的使用,注意where的条件,一开始我就写错了
select 
seat_id
from 
(
select
seat_id,free,
lag(free,1,0) over(order by seat_id) as pre,
lead(free,1,0) over(order by seat_id) as nex
from
cinema
)t
where free =1 and  (pre =1 or nex =1)
order by seat_id
sql
--官方的自连接和绝对值函数的使用
select distinct(c1.seat_id) 
from cinema c1 join cinema c2
on    abs(c2.seat_id-c1.seat_id)=1
where c1.free=1 and c2.free=1
order by c1.seat_id

32.销售员(left join与子查询) ☆

输出所有表 salesperson 中,没有向公司 'RED' 销售任何东西的销售员。

描述

给定 3 个表: salesperson, company, orders。
输出所有表 salesperson 中,没有向公司 'RED' 销售任何东西的销售员。

示例:
输入

表: salesperson

text
+----------+------+--------+-----------------+-----------+
| sales_id | name | salary | commission_rate | hire_date |
+----------+------+--------+-----------------+-----------+
|   1      | John | 100000 |     6           | 4/1/2006  |
|   2      | Amy  | 120000 |     5           | 5/1/2010  |
|   3      | Mark | 65000  |     12          | 12/25/2008|
|   4      | Pam  | 25000  |     25          | 1/1/2005  |
|   5      | Alex | 50000  |     10          | 2/3/2007  |
+----------+------+--------+-----------------+-----------+

表 salesperson 存储了所有销售员的信息。每个销售员都有一个销售员编号 sales_id 和他的名字 name 。

表: company

text
+---------+--------+------------+
| com_id  |  name  |    city    |
+---------+--------+------------+
|   1     |  RED   |   Boston   |
|   2     | ORANGE |   New York |
|   3     | YELLOW |   Boston   |
|   4     | GREEN  |   Austin   |
+---------+--------+------------+

表 company 存储了所有公司的信息。每个公司都有一个公司编号 com_id 和它的名字 name 。
表: orders

text
+----------+------------+---------+----------+--------+
| order_id | order_date | com_id  | sales_id | amount |
+----------+------------+---------+----------+--------+
| 1        |   1/1/2014 |    3    |    4     | 100000 |
| 2        |   2/1/2014 |    4    |    5     | 5000   |
| 3        |   3/1/2014 |    1    |    1     | 50000  |
| 4        |   4/1/2014 |    1    |    4     | 25000  |
+----------+----------+---------+----------+--------+

表 orders 存储了所有的销售数据,包括销售员编号 sales_id 和公司编号 com_id 。
输出

text
+------+
| name | 
+------+
| Amy  | 
| Mark | 
| Alex |
+------+

解释
根据表 orders 中的订单 '3' 和 '4' ,容易看出只有 'John' 和 'Pam' 两个销售员曾经向公司 'RED' 销售过。
所以我们需要输出表 salesperson 中所有其他人的名字。

sql
--我的写法,这题有坑不简单
select 
distinct salesperson.name as name 
from
salesperson
left join orders
on 
orders.sales_id  = salesperson.sales_id
left join company
on
orders.com_id = company.com_id
group by
salesperson.name
having
sum(if(company.name = "RED", 1, 0))  = 0
sql
-- 使用子查询
select 
name 
from 
salesperson
where sales_id  not in 
(
select
sales_id
from
company
join orders
on company.com_id = orders.com_id
where company.name = "RED"
)

33.树节点

给定一个表 tree,id 是树节点的编号, p_id 是它父节点的 id 。

text
+----+------+
| id | p_id |
+----+------+
| 1  | null |
| 2  | 1    |
| 3  | 1    |
| 4  | 2    |
| 5  | 2    |
+----+------+

树中每个节点属于以下三种类型之一:

叶子:如果这个节点没有任何孩子节点。
根:如果这个节点是整棵树的根,即没有父节点。
内部节点:如果这个节点既不是叶子节点也不是根节点。
 

写一个查询语句,输出所有节点的编号和节点的类型,并将结果按照节点编号排序。上面样例的结果为:

text
+----+------+
| id | Type |
+----+------+
| 1  | Root |
| 2  | Inner|
| 3  | Leaf |
| 4  | Leaf |
| 5  | Leaf |
+----+------+
sql
-- 我的写法case when 注意null是字符串还是null
select 
distinct 
t.id,
case 
when  t.p_id is null  then 'Root'
when  t1.p_id is not null then 'Inner'
when  t1.p_id is null then 'Leaf'
end as Type
from 
tree t
left join tree t1
on t.id = t1.p_id
sql
-- 使用子查询
SELECT ID,
       CASE WHEN P_ID IS NULL THEN 'Root'
            WHEN ID IN (SELECT P_ID FROM TREE) THEN 'Inner'
            ELSE 'Leaf' END AS TYPE
FROM TREE;

我以前觉得case when就是分类讨论,其实不然,case when 是这样的,先判断第一个,如果不满足,判断第二个,以此类推,而不是分类讨论并列关系

34.判断三角形

假设表 triangle 保存了所有三条线段的长度 x、y、z ,请你帮 Tim 写一个查询语句,来判断每组 x、y、z 是否可以组成一个三角形?

sql
--我的写法,简单题
select
x,y,z,
case 
when x+y > z and x+z >y and y+z >x then 'Yes'
else 'No' end  as  triangle
from 
triangle

35.平面上的最近距离(where的写法)

写一个查询语句找到两点之间的最近距离,保留 2 位小数。

sql
-- 我的写法,简单题函数的应用,注意对笛卡尔积的优化
select
round(sqrt(min((pow(t1.x - t2.x, 2) + pow(t1.y - t2.y, 2)))),2) as shortest
from
point_2d t1
join point_2d t2
on t1.x <> t2.x or t1.y <> t2.y
sql
-- 学习where的这种写法
select round(min(sqrt(power(p1.x-p2.x,2) + power(p1.y-p2.y,2))),2) shortest
from point_2d p1, point_2d p2 
where (p1.x, p1.y) <> (p2.x,p2.y)

36.直线上的最近距离

写一个查询语句,找到点中最近两个点之间的距离

sql
-- 简单题我的写法,可以使用min但是速度是一样的.
select
abs(t1.x - t2.x) as shortest 
from
point t1
join 
point t2
on t1.x <> t2.x
order by shortest
limit 1

37.二级关注者

在 facebook 中,表 follow 会有 2 个字段: followee, follower ,分别表示被关注者和关注者。

请写一个 sql 查询语句,对每一个关注者,查询关注他的关注者的数目。

比方说:

text
+-------------+------------+
| followee    | follower   |
+-------------+------------+
|     A       |     B      |
|     B       |     C      |
|     B       |     D      |
|     D       |     E      |
+-------------+------------+

应该输出:

text
+-------------+------------+
| follower    | num        |
+-------------+------------+
|     B       |  2         |
|     D       |  1         |
+-------------+------------+
sql
-- 万万没想到要去重,注意join的条件即可,简单题
select
f1.follower as follower,count(distinct f2.follower) as num 
from
follow f1
join 
follow f2 
on f1.follower = f2.followee
group by f1.follower
      

38.平均工资(☆)

给如下两个表,写一个查询语句,求出在每一个工资发放日,每个部门的平均工资与公司的平均工资的比较结果 (高 / 低 / 相同)。

表: salary

text
| id | employee_id | amount | pay_date   |
|----|-------------|--------|------------|
| 1  | 1           | 9000   | 2017-03-31 |
| 2  | 2           | 6000   | 2017-03-31 |
| 3  | 3           | 10000  | 2017-03-31 |
| 4  | 1           | 7000   | 2017-02-28 |
| 5  | 2           | 6000   | 2017-02-28 |
| 6  | 3           | 8000   | 2017-02-28 |

employee_id 字段是表 employee 中 employee_id 字段的外键。

text
| employee_id | department_id |
|-------------|---------------|
| 1           | 1             |
| 2           | 2             |
| 3           | 2             |

对于如上样例数据,结果为:

text
| pay_month | department_id | comparison  |
|-----------|---------------|-------------|
| 2017-03   | 1             | higher      |
| 2017-03   | 2             | lower       |
| 2017-02   | 1             | same        |
| 2017-02   | 2             | same        |
sql
--我的写法:窗口写法,读错题意了,读懂题意!!!,题目是求的每个月份的情况
检查了好久要去重.......而且要在外面的那个select来去重?发生了什么
值得注意的一点就是一个月内可能会发多次工资,所以partition的条件应该要是格式化的那个日期
select
distinct
pay_month,
department_id,
case
when dept_avg > com_avg then 'higher'
when dept_avg < com_avg then 'lower'
else 'same'
end as  comparison
from
(
select
//distinct
department_id,
to_char(pay_date,'YYYY-MM')  as pay_month ,
avg(amount) over(partition by pay_date) com_avg,
avg(amount) over(partition by pay_date, department_id) dept_avg
from
salary
join 
employee
on salary.employee_id = employee.employee_id
) t
order by pay_month desc ,department_id
sql
--group by写法,这里的join条件是日期,总感觉哪里不对
select 
t1.day_month as pay_month,
department_id,
case
when avg_amount1 > avg_amount then 'higher'
when avg_amount1 < avg_amount then 'lower'
else 'same'
end as  comparison
from 
(
select
avg(amount)  as avg_amount,
date_format(pay_date, '%Y-%m') as day_month
from
salary
group by 
date_format(pay_date, '%Y-%m')
) t1
join 
(
select 
avg(amount)  as avg_amount1,
department_id,
date_format(pay_date, '%Y-%m') as day_month
from 
employee
join salary on employee.employee_id = salary.employee_id
group by date_format(pay_date, '%Y-%m') ,department_id
) t2
on t1.day_month = t2.day_month

学习使用Oracle中的tochar()来格式化日期还有使用replace和substr也可以格式化日期

39.学生地理信息报告(☆)

写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。数据保证来自美洲的学生不少于来自亚洲或者欧洲的学生。

一所美国大学有来自亚洲、欧洲和美洲的学生,他们的地理信息存放在如下 student 表中。

text
| name   | continent |
|--------|-----------|
| Jack   | America   |
| Pascal | Europe    |
| Xi     | Asia      |
| Jane   | America   |

写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。数据保证来自美洲的学生不少于来自亚洲或者欧洲的学生。

对于样例输入,它的对应输出是:

text
| America | Asia | Europe |
|---------|------|--------|
| Jack    | Xi   | Pascal |
| Jane    |      |        |

进阶:如果不能确定哪个大洲的学生数最多,你可以写出一个查询去生成上述学生报告吗?

sql
-- 写过类似的题,一开始忘记使用聚合函数了,为什么要用序列函数,因为group by 在一个组内不会出现相同的大洲
select
     max(case when continent='America' then name else null end) as America
    ,max(case when continent='Asia' then name else null end) as Asia
    ,max(case when continent='Europe' then name else null end) as Europe
from(
    select row_number() over(partition by continent order by name) as rn,name,continent from student
) t
group by rn
order by rn 
sql
-- 分别查询每个大洲在left join
select America,Asia,Europe
from (select row_number() over(order by name) id,name as America from student where continent = 'America') a
left join (select row_number() over(order by name) id,name as Asia from student where continent = 'Asia') b
on a.id=b.id
left join (select row_number() over(order by name) id,name as Europe from student where continent = 'Europe') c
on a.id=c.id

40.只出现一次的最大数字

你能写一个 SQL 查询语句,找到只出现过一次的数字中,最大的一个数字吗?

sql
-- 我的写法
-- 注意null的处理
select
max(num) as num 
from
(
select
num 
from 
my_numbers
group by num 
having count(1) =1
) t
sql
-- 注意条件查询不会返回null,使用ifnull或者嵌套select
select num from my_numbers group by num having count(*)=1 
order by num desc limit 1

练习题 4

41.有趣的电影(位运算)

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列
例如,下表 cinema:

text
+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   1     | War       |   great 3D   |   8.9     |
|   2     | Science   |   fiction    |   8.5     |
|   3     | irish     |   boring     |   6.2     |
|   4     | Ice song  |   Fantacy    |   8.6     |
|   5     | House card|   Interesting|   9.1     |
+---------+-----------+--------------+-----------+

对于上面的例子,则正确的输出是为:

text
+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
+---------+-----------+--------------+-----------+
sql
-- 我的写法,简单题
select 
id,movie,description,rating
from
cinema
where description != 'boring' and (id%2 =1)
order by rating desc
sql
-- 注意这种写法与位运算
select id, movie, description, rating
from cinema
where description <> 'boring' and id & 1
order by rating desc;

42.换座位

小美想改变相邻俩学生的座位。
你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的

小美想改变相邻俩学生的座位。

你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

示例:

text
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+

假如数据输入的是上表,则输出结果如下:

text
+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+

注意:

如果学生人数是奇数,则不需要改变最后一个同学的座位。

sql
--我的写法两个偏移量函数的使用
select 
id,
case when mod(id,2) = 1 then lead1  else lag1 end as student
from 
(
select
id,
lag(student,1,student) over(order by id) as lag1,
lead(student,1,student) over(order by id) as lead1
from
seat
) 

评论区的一些写法

sql
-- 对id进行判断,根据条件如果为奇数且是最后一个则不改变
SELECT (CASE 
            WHEN MOD(id,2) = 1 AND id = (SELECT COUNT(*) FROM seat) THEN id
            WHEN MOD(id,2) = 1 THEN id+1
            ElSE id-1
        END) AS id, student
FROM seat
ORDER BY id;
sql
-- 妙,思路是对id-1把偶数转变为奇数,使用位运算,偶数+1 奇数-1
select rank() over(order by (id-1)^1) as id,student from seat

43.更变性别

给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。
注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。

text
-- 简答题,熟悉一下语法
update salary set sex=if(sex='f','m','f')
text
UPDATE salary 

SET 
   sex = CASE sex 
        WHEN "m" THEN "f" 
        ELSE "m" 
    END;
sql
ALTER TABLE salary 
ADD COLUMN sexadd TEXT
UPDATE salary 
SET sexadd = sex
SET sex = "f"
WHERE sex = "m"
SET sex = "m"
WHERE sexadd = "f";

44.买下所有产品的客户

Customer 表:

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+

product_key 是 Customer 表的外键。
Product 表:

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_key | int     |
+-------------+---------+

product_key 是这张表的主键。
 

写一条 SQL 查询语句,从 Customer 表中查询购买了 Product 表中所有产品的客户的 id。

示例:

Customer 表:

text
+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1           | 5           |
| 2           | 6           |
| 3           | 5           |
| 3           | 6           |
| 1           | 6           |
+-------------+-------------+

Product 表:

text
+-------------+
| product_key |
+-------------+
| 5           |
| 6           |
+-------------+

Result 表:

text
+-------------+
| customer_id |
+-------------+
| 1           |
| 3           |
+-------------+

购买了所有产品(5 和 6)的客户的 id 是 1 和 3

sql
-- 我的写法注意去重,可以对去重优化一下
select
customer_id
from
(
select
distinct customer_id,product_key
from
Customer
) t
group by customer_id
having count(1) = (select count(1) from Product )
sql
select
customer_id
from
Customer
group by customer_id
having count(distinct product_key ) = (select count(1) from  Product )

45.合作过至少三次的演员和导演

sql
-- 简单题,注意如果使用concat两个字段在这一题中要加","
select 
actor_id,director_id
from
ActorDirector
group by actor_id , director_id
having count(1) >=3

46.产品销售分析1

sql
-- 简单题
select 
product_name,year,price
from 
Product t1
join 
Sales t2
on t1. product_id = t2.product_id

47.产品销售分析2

sql
--简单题,不用join...
select 
t1.product_id,sum(quantity) as  total_quantity 
from
Product t1
join Sales t2
on t1.product_id = t2.product_id
group by t1.product_id

48.产品销售分析3(where联合字段)

sql
-- 简答题
select 
product_id,year as first_year  ,quantity,price 
from 
(
select
product_id,year,quantity,price ,
rank() over(partition by product_id order by year) as rn 
from
Sales 
)  t 
where rn =1
sql
-- where联合字段与子查询
SELECT PRODUCT_ID, YEAR AS FIRST_YEAR, QUANTITY, PRICE
FROM SALES
WHERE (PRODUCT_ID, YEAR) IN (SELECT PRODUCT_ID, MIN(YEAR)
                             FROM SALES
                             GROUP BY 1);

49.项目员工1

项目表 Project: 

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| project_id  | int     |
| employee_id | int     |
+-------------+---------+

主键为 (project_id, employee_id)。
employee_id 是员工表 Employee 表的外键。
员工表 Employee:

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| employee_id      | int     |
| name             | varchar |
| experience_years | int     |
+------------------+---------+

主键是 employee_id。
 

请写一个 SQL 语句,查询每一个项目中员工的 平均 工作年限,精确到小数点后两位。

查询结果的格式如下:

Project 表:

text
+-------------+-------------+
| project_id  | employee_id |
+-------------+-------------+
| 1           | 1           |
| 1           | 2           |
| 1           | 3           |
| 2           | 1           |
| 2           | 4           |
+-------------+-------------+

Employee 表:

text
+-------------+--------+------------------+
| employee_id | name   | experience_years |
+-------------+--------+------------------+
| 1           | Khaled | 3                |
| 2           | Ali    | 2                |
| 3           | John   | 1                |
| 4           | Doe    | 2                |
+-------------+--------+------------------+

Result 表:

text
+-------------+---------------+
| project_id  | average_years |
+-------------+---------------+
| 1           | 2.00          |
| 2           | 2.50          |
+-------------+---------------+

第一个项目中,员工的平均工作年限是 (3 + 2 + 1) / 3 = 2.00;第二个项目中,员工的平均工作年限是 (3 + 2) / 2 = 2.50

sql
-- 简单题,注意SQL中的格式化问题
select
project_id,
round(avg(experience_years),2) as average_years
from 
Project t1
join Employee t2
on t1.employee_id =t2.employee_id
group by project_id

50.项目员工2

sql
-- 我的写法,简单题,注意可能会有并列第一
select 
project_id
from 
(
select
project_id,dense_rank() over(order by count(1) desc) as rn 
from 
Project
group by project_id
)
where rn =1
sql
-- 使用子查询,学习使用all的用法
SELECT PROJECT_ID
FROM PROJECT
GROUP BY 1
HAVING COUNT(*) = (SELECT COUNT(*)
                   FROM PROJECT
                   GROUP BY PROJECT_ID
                   ORDER BY 1 DESC
                   LIMIT 1);

METHOD 2
SELECT PROJECT_ID
FROM PROJECT
GROUP BY 1
HAVING COUNT(*) >= ALL (SELECT COUNT(*)
                        FROM PROJECT
                        GROUP BY PROJECT_ID);

练习题 5

51.项目员工3

写 一个 SQL 查询语句,报告在每一个项目中经验最丰富的雇员是谁。如果出现经验年数相同的情况,请报告所有具有最大经验年数的员工。

项目表 Project:

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| project_id  | int     |
| employee_id | int     |
+-------------+---------+

(project_id, employee_id) 是这个表的主键
employee_id 是员工表 Employee 的外键
员工表 Employee:

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| employee_id      | int     |
| name             | varchar |
| experience_years | int     |
+------------------+---------+

employee_id 是这个表的主键
 
写 一个 SQL 查询语句,报告在每一个项目中经验最丰富的雇员是谁。如果出现经验年数相同的情况,请报告所有具有最大经验年数的员工。

查询结果格式在以下示例中:

Project 表:

text
+-------------+-------------+
| project_id  | employee_id |
+-------------+-------------+
| 1           | 1           |
| 1           | 2           |
| 1           | 3           |
| 2           | 1           |
| 2           | 4           |
+-------------+-------------+

Employee 表:

text
+-------------+--------+------------------+
| employee_id | name   | experience_years |
+-------------+--------+------------------+
| 1           | Khaled | 3                |
| 2           | Ali    | 2                |
| 3           | John   | 3                |
| 4           | Doe    | 2                |
+-------------+--------+------------------+

Result 表:

text
+-------------+---------------+
| project_id  | employee_id   |
+-------------+---------------+
| 1           | 1             |
| 1           | 3             |
| 2           | 1             |
+-------------+---------------+

employee_id 为 1 和 3 的员工在 project_id 为 1 的项目中拥有最丰富的经验。在 project_id 为 2 的项目中,employee_id 为 1 的员工拥有最丰富的经验。

sql
--我的窗口写法
select 
project_id,t.employee_id
from 
(
select 
t1.employee_id ,
project_id,
dense_rank() over(partition by project_id order by experience_years desc ) as rn 
from
Employee t1
join Project  t2
on t1.employee_id = t2.employee_id
) t
where rn =1
sql
-- 使用子查询,先查找出每个项目中最大工龄
//max聚合函数只返回一条记录,用where的联合字段获取分组最大值
select p.project_id, p.employee_id
from Project as p inner join Employee as e on p.employee_id = e.employee_id
where (p.project_id, e.experience_years) in (select p.project_id, max(experience_years)
                                            from Project as p inner join Employee as e
                                            on p.employee_id = e.employee_id
                                            group by p.project_id)

52.销售分析1

编写一个 SQL 查询,查询总销售额最高的销售者,如果有并列的,就都展示出来

产品表:Product

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
| unit_price   | int     |
+--------------+---------+

product_id 是这个表的主键.
销售表:Sales

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| seller_id   | int     |
| product_id  | int     |
| buyer_id    | int     |
| sale_date   | date    |
| quantity    | int     |
| price       | int     |
+------ ------+---------+

这个表没有主键,它可以有重复的行.
product_id 是 Product 表的外键.
 

编写一个 SQL 查询,查询总销售额最高的销售者,如果有并列的,就都展示出来。

查询结果格式如下所示:

Product 表:

text
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1          | S8           | 1000       |
| 2          | G4           | 800        |
| 3          | iPhone       | 1400       |
+------------+--------------+------------+

Sales 表:

text
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date  | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
| 2         | 2          | 3        | 2019-06-02 | 1        | 800   |
| 3         | 3          | 4        | 2019-05-13 | 2        | 2800  |
+-----------+------------+----------+------------+----------+-------+

Result 表:

text
+-------------+
| seller_id   |
+-------------+
| 1           |
| 3           |
+-------------+

Id 为 1 和 3 的销售者,销售总金额都为最高的 2800

sql
-- 我的写法窗口写法,简单题
select 
seller_id
from 
(
select
seller_id,
dense_rank() over(order by sum(price) desc) as rn 
from
Sales
group by seller_id
) t
where rn =1
sql
-- all的用法
select
seller_id
from 
Sales
group by 
seller_id
having sum(price) >= all( select sum(price) from Sales group by seller_id order by sum(price) desc )

53.销售分析2(☆)

编写一个 SQL 查询,查询购买了 S8 手机却没有购买 iPhone 的买家。注意这里 S8 和 iPhone 是 Product 表中的产品。

sql
-- 我的写法,过去笨拙..
with x as (
select
buyer_id,product_name
from
Product t1 join  Sales t2 on t1.product_id = t2.product_id
)
select
buyer_id
from
(
select
distinct
buyer_id 
from 
x
where product_name = 'S8'                                                            
union all 
(
select 
distinct
buyer_id 
from 
x
where buyer_id not in (select buyer_id from x where product_name = 'iPhone')
)
) t3
group by  buyer_id having count(1) >1
sql
--哇!!没想到...
-- sum方法
select
buyer_id
from 
Sales t1
join Product t2
on t1.product_id = t2.product_id
group by buyer_id
having sum(product_name = 'S8') >0 and sum(product_name = 'iPhone') =0
sql
-- where的嵌套
select distinct buyer_id
from Sales
where buyer_id not in (
    select buyer_id
    from Product p,Sales s
    where p.product_id = s.product_id
    and p.product_name = 'iPhone'
) 
and buyer_id in (
    select buyer_id
    from Product p,Sales s
    where p.product_id = s.product_id
    and p.product_name = 'S8'
)

54.销售分析3

编写一个SQL查询,报告2019年春季才售出的产品。即仅在2019-01-01至2019-03-31(含)之间出售的商品。

sql
-- 我的写法
select 
t2.product_id,product_name
from 
Product t1
join 
(
select
product_id
from 
Sales
group by product_id
having sum( if( sale_date between date_format('2019-01-01','%Y-%m-%d') and date_format('2019-03-31','%Y-%m-%d'),0,1) ) = 0 
) t2
on t1.product_id = t2.product_id
sql
-- 学习一下METHOD 1,我怎么想不到....
METHOD 1
SELECT P.PRODUCT_ID, PRODUCT_NAME
FROM PRODUCT AS P
INNER JOIN SALES AS S
ON P.PRODUCT_ID = S.PRODUCT_ID
GROUP BY 1
HAVING MIN(SALE_DATE) >= '2019-01-01'
AND MAX(SALE_DATE) <= '2019-03-31';

METHOD 2
-- 说明既要满足存在于条件一,又要满足存在于条件二
SELECT PRODUCT_ID, PRODUCT_NAME
FROM PRODUCT
WHERE PRODUCT_ID IN (SELECT PRODUCT_ID
                     FROM SALES
                     WHERE SALE_DATE BETWEEN '2019-01-01' AND '2019-03-31')
AND PRODUCT_ID NOT IN (SELECT PRODUCT_ID
                       FROM SALES
                       WHERE SALE_DATE < '2019-01-01'
                       OR SALE_DATE > '2019-03-31');

上面的三道题目使用not in 把我绕糊涂了...学习一下在having中使用sum ,if 之类的过滤条件的使用,来替换not in where用法

55.游戏的玩法5(min的窗口的使用)☆

编写一个 SQL 查询,报告每个安装日期、当天安装游戏的玩家数量和第一天的留存时间。

Activity 活动记录表

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+

(player_id,event_date)是此表的主键
这张表显示了某些游戏的玩家的活动情况
每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0)
 

我们将玩家的安装日期定义为该玩家的第一个登录日。

我们还将某个日期 X 的第 1 天留存时间定义为安装日期为 X 的玩家的数量,他们在 X 之后的一天重新登录,除以安装日期为 X 的玩家的数量,四舍五入到小数点后两位。

编写一个 SQL 查询,报告每个安装日期、当天安装游戏的玩家数量和第一天的留存时间。

查询结果格式如下所示:

Activity 表:

text
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-03-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-01 | 0            |
| 3         | 4         | 2016-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result 表:

text
+------------+----------+----------------+
| install_dt | installs | Day1_retention |
+------------+----------+----------------+
| 2016-03-01 | 2        | 0.50           |
| 2017-06-25 | 1        | 0.00           |
+------------+----------+----------------+

玩家 1 和 3 在 2016-03-01 安装了游戏,但只有玩家 1 在 2016-03-02 重新登录,所以 2016-03-01 的第一天留存时间是 1/2=0.50
玩家 2 在 2017-06-25 安装了游戏,但在 2017-06-26 没有重新登录,因此 2017-06-25 的第一天留存时间为 0/1=0.00

sql
-- 我的写法超时了...优化一下
--我的思路先获取每个用户首次登录的日期作为A
-- 以上表A的字段与原始表join,条件是用户相等,且时间差一天,获取的是留存信息,然后group by 首次登录的日期两张表join获取答案...
select 
x1.event_date as install_dt  ,s1 as installs , nvl(s2/s1,0) as Day1_retention
from
(
select 
event_date,count(1) as s1
from 
(
select
player_id,min(to_char(event_date,'yyyy-mm-dd')) as event_date
from
Activity
group by player_id
) t1
group by event_date ) x1
left join 
(
select 
t2.event_date,count(1) as s2
from 
(
select
player_id,min(to_char(event_date,'yyyy-mm-dd')) as event_date
from
Activity
group by player_id
) t2
join 
Activity 
on t2.player_id = Activity.player_id and t2.event_date = to_char(Activity.event_date -1 ,'yyyy-mm-dd')
group by t2.event_date ) x2
on x1.event_date = x2.event_date
sql
-- 使用窗口函数,哇没想到.....
select install_dt,count(distinct player_id)installs,
       round(sum(if(datediff(event_date,install_dt)=1,1,0))/count(distinct player_id),2) Day1_retention 
from 
(
    select *,min(event_date) over(partition by player_id) install_dt
    from Activity
)t1   
group by install_dt
sql
select a1.install_dt,
       count(*) installs,
       round(count(a2.event_date)/count(*),2) Day1_retention
from(
    select player_id,min(event_date) install_dt
    from Activity
    group by player_id
) a1
left join Activity a2
    on a1.player_id = a2.player_id and datediff(a2.event_date,a1.install_dt)=1
group by a1.install_dt
sql
select
    A1.event_date as install_dt,
    count(*) as installs,
    round(count(A2.event_date) / count(*)*1.0 , 2) as Day1_retention

from Activity A1
left join Activity A2
    on A1.player_id = A2.player_id
    and A1.event_date = DATE_ADD(A2.event_date, INTERVAL -1 day)
where (A1.player_id, A1.event_date) in (select player_id, min(event_date) 
                                        from Activity 
                                        group by player_id)
group by A1.event_date
order by 1

56.小众书籍(on 和 where的区别)

你需要写一段 SQL 命令,筛选出过去一年中订单总量 少于10本 的 书籍 。
注意:不考虑 上架(available from)距今 不满一个月 的书籍。并且 假设今天是 2019-06-23 。

sql
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| book_id        | int     |
| name           | varchar |
| available_from | date    |
+----------------+---------+
book_id 是这个表的主键。
订单表 Orders:

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| order_id       | int     |
| book_id        | int     |
| quantity       | int     |
| dispatch_date  | date    |
+----------------+---------+
order_id 是这个表的主键。
book_id  是 Books 表的外键。
 

你需要写一段 SQL 命令,筛选出过去一年中订单总量 少于10本 的 书籍 。

注意:不考虑 上架(available from)距今 不满一个月 的书籍。并且 假设今天是 2019-06-23 。

 

下面是样例输出结果:

Books 表:
+---------+--------------------+----------------+
| book_id | name               | available_from |
+---------+--------------------+----------------+
| 1       | "Kalila And Demna" | 2010-01-01     |
| 2       | "28 Letters"       | 2012-05-12     |
| 3       | "The Hobbit"       | 2019-06-10     |
| 4       | "13 Reasons Why"   | 2019-06-01     |
| 5       | "The Hunger Games" | 2008-09-21     |
+---------+--------------------+----------------+

Orders 表:
+----------+---------+----------+---------------+
| order_id | book_id | quantity | dispatch_date |
+----------+---------+----------+---------------+
| 1        | 1       | 2        | 2018-07-26    |
| 2        | 1       | 1        | 2018-11-05    |
| 3        | 3       | 8        | 2019-06-11    |
| 4        | 4       | 6        | 2019-06-05    |
| 5        | 4       | 5        | 2019-06-20    |
| 6        | 5       | 9        | 2009-02-02    |
| 7        | 5       | 8        | 2010-04-13    |
+----------+---------+----------+---------------+

Result 表:
+-----------+--------------------+
| book_id   | name               |
+-----------+--------------------+
| 1         | "Kalila And Demna" |
| 2         | "28 Letters"       |
| 5         | "The Hunger Games" |
+-----------+--------------------+
sql
-- 这题有毒,提交了5,6次
select b.book_id,b.name
from
books b left join orders o
on 
b.book_id=o.book_id
where
b.available_from<'2019-05-23'
group by b.book_id
having ifnull(sum(if(o.dispatch_date<'2018-06-23',0,quantity)),0)<10
order by b.book_id

注意条件中on 和 where的区别
1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。
书籍表 Books:
例如:

sql
select b.book_id, b.name
from books b left join orders o on b.book_id = o.book_id and  o.dispatch_date >= '2018-06-23'
where b.available_from < '2019-05-23'
group by b.book_id
having ifnull(sum(o.quantity),0) < 10

57.每日新用户统计

编写一个 SQL 查询,以查询从今天起最多 90 天内,每个日期该日期首次登录的用户数。假设今天是 2019-06-30

Traffic 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| activity      | enum    |
| activity_date | date    |
+---------------+---------+

该表没有主键,它可能有重复的行。
activity 列是 ENUM 类型,可能取 ('login', 'logout', 'jobs', 'groups', 'homepage') 几个值之一。

编写一个 SQL 查询,以查询从今天起最多 90 天内,每个日期该日期首次登录的用户数。假设今天是 2019-06-30.

查询结果格式如下例所示:

Traffic 表:

text
+---------+----------+---------------+
| user_id | activity | activity_date |
+---------+----------+---------------+
| 1       | login    | 2019-05-01    |
| 1       | homepage | 2019-05-01    |
| 1       | logout   | 2019-05-01    |
| 2       | login    | 2019-06-21    |
| 2       | logout   | 2019-06-21    |
| 3       | login    | 2019-01-01    |
| 3       | jobs     | 2019-01-01    |
| 3       | logout   | 2019-01-01    |
| 4       | login    | 2019-06-21    |
| 4       | groups   | 2019-06-21    |
| 4       | logout   | 2019-06-21    |
| 5       | login    | 2019-03-01    |
| 5       | logout   | 2019-03-01    |
| 5       | login    | 2019-06-21    |
| 5       | logout   | 2019-06-21    |
+---------+----------+---------------+

Result 表:

text
+------------+-------------+
| login_date | user_count  |
+------------+-------------+
| 2019-05-01 | 1           |
| 2019-06-21 | 2           |
+------------+-------------+

请注意,我们只关心用户数非零的日期.
ID 为 5 的用户第一次登陆于 2019-03-01,因此他不算在 2019-06-21 的的统计内。

sql
--我的写法为什么不能直接-90天,?简单题
select 
login_date,count(1) as user_count
from 
(
select
 user_id,min(activity_date) as login_date
from
Traffic
where activity ='login'
group by 
user_id
) t1
where datediff("2019-06-30",login_date) <= 90
group by login_date

mysql中的date_sub('2019-06-30', interval 90 day)用法

58.每位学生的最高成绩

编写一个 SQL 查询,查询每位学生获得的最高成绩和它所对应的科目,若科目成绩并列,取 course_id 最小的一门。查询结果需按 student_id 增序进行排序。

表:Enrollments

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| course_id     | int     |
| grade         | int     |
+---------------+---------+

(student_id, course_id) 是该表的主键。

编写一个 SQL 查询,查询每位学生获得的最高成绩和它所对应的科目,若科目成绩并列,取 course_id 最小的一门。查询结果需按 student_id 增序进行排序。

查询结果格式如下所示:

Enrollments 表:

text
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 2          | 2         | 95    |
| 2          | 3         | 95    |
| 1          | 1         | 90    |
| 1          | 2         | 99    |
| 3          | 1         | 80    |
| 3          | 2         | 75    |
| 3          | 3         | 82    |
+------------+-----------+-------+

Result 表:

text
+------------+-------------------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 1          | 2         | 99    |
| 2          | 2         | 95    |
| 3          | 3         | 82    |
+------------+-----------+-------+
sql
--我的写法,窗口简单题
select 
student_id,course_id,grade
from 
(
select 
student_id,course_id,grade,
row_number() over(partition by student_id order by grade desc ,course_id asc) as rn 
from 
Enrollments
) t1
where rn =1
order by student_id
sql
select student_id,min(course_id) as course_id,grade
from Enrollments
where (student_id,grade) in 
    (select student_id,max(grade) from Enrollments group by student_id)
group by student_id, grade

59.报告的记录

编写一条SQL,查询每种 报告理由(report reason)在昨天的不同报告数量(post_id)。假设今天是 2019-07-05。

动作表:Actions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| post_id       | int     |
| action_date   | date    | 
| action        | enum    |
| extra         | varchar |
+---------------+---------+

此表没有主键,所以可能会有重复的行。
action 字段是 ENUM 类型的,包含:('view', 'like', 'reaction', 'comment', 'report', 'share')
extra 字段是可选的信息(可能为 null),其中的信息例如有:1.报告理由(a reason for report) 2.反应类型(a type of reaction)
 

编写一条SQL,查询每种 报告理由(report reason)在昨天的不同报告数量(post_id)。假设今天是 2019-07-05。

查询及结果的格式示例:

Actions table:

text
+---------+---------+-------------+--------+--------+
| user_id | post_id | action_date | action | extra  |
+---------+---------+-------------+--------+--------+
| 1       | 1       | 2019-07-01  | view   | null   |
| 1       | 1       | 2019-07-01  | like   | null   |
| 1       | 1       | 2019-07-01  | share  | null   |
| 2       | 4       | 2019-07-04  | view   | null   |
| 2       | 4       | 2019-07-04  | report | spam   |
| 3       | 4       | 2019-07-04  | view   | null   |
| 3       | 4       | 2019-07-04  | report | spam   |
| 4       | 3       | 2019-07-02  | view   | null   |
| 4       | 3       | 2019-07-02  | report | spam   |
| 5       | 2       | 2019-07-04  | view   | null   |
| 5       | 2       | 2019-07-04  | report | racism |
| 5       | 5       | 2019-07-04  | view   | null   |
| 5       | 5       | 2019-07-04  | report | racism |
+---------+---------+-------------+--------+--------+

Result table:

text
+---------------+--------------+
| report_reason | report_count |
+---------------+--------------+
| spam          | 1            |
| racism        | 2            |
+---------------+--------------+ 

注意,我们只关心报告数量非零的结果

sql
--我的答案
select 
extra report_reason,count(distinct if(post_id !=0,post_id,null) ) as report_count
from 
Actions
where  action_date ='2019-07-04' and action = 'report' 
group by extra
having report_reason is not null

注意count(distinct 字段的用法)count和null(空值)
count(?) ,即计算某个字段的时候,并不计算空值

text
1	0
1	2
1	2
sql
-- 1
select count(distinct if(ag != 0,ag,null))
from tb_aaa
group by id; 

-- 2
select count(distinct ag )
from tb_aaa
group by id;

60.查询活跃业务

写一段 SQL 来查询所有活跃的业务
如果一个业务的某个事件类型的发生次数大于此事件类型在所有业务中的平均发生次数,并且该业务至少有两个这样的事件类型,那么该业务就可被看做是活跃业务

事件表:Events

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| business_id   | int     |
| event_type    | varchar |
| occurences    | int     | 
+---------------+---------+

此表的主键是 (business_id, event_type)。
表中的每一行记录了某种类型的事件在某些业务中多次发生的信息。
 

写一段 SQL 来查询所有活跃的业务。

如果一个业务的某个事件类型的发生次数大于此事件类型在所有业务中的平均发生次数,并且该业务至少有两个这样的事件类型,那么该业务就可被看做是活跃业务。

查询结果格式如下所示:

Events table:

text
+-------------+------------+------------+
| business_id | event_type | occurences |
+-------------+------------+------------+
| 1           | reviews    | 7          |
| 3           | reviews    | 3          |
| 1           | ads        | 11         |
| 2           | ads        | 7          |
| 3           | ads        | 6          |
| 1           | page views | 3          |
| 2           | page views | 12         |
+-------------+------------+------------+

结果表

text
+-------------+
| business_id |
+-------------+
| 1           |
+-------------+ 

'reviews'、 'ads' 和 'page views' 的总平均发生次数分别是 (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5。
id 为 1 的业务有 7 个 'reviews' 事件(大于 5)和 11 个 'ads' 事件(大于 8),所以它是活跃业务。

sql
--终于执行对了,简单题,leedcode的Oracle有毒,好像不支持if...?
select 
business_id
from 
(
select
business_id,event_type,occurences,
avg(occurences) over(partition by event_type )  as rn
from
Events
) t1
where occurences > rn
group by business_id
having count(distinct event_type) >=2

练习题 6

61.用户购买平台(☆)

写一段 SQL 来查找每天 仅 使用手机端用户、仅 使用桌面端用户和 同时 使用桌面端和手机端的用户人数和总支出金额。

支出表: Spending

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| spend_date  | date    |
| platform    | enum    | 
| amount      | int     |
+-------------+---------+

这张表记录了用户在一个在线购物网站的支出历史,该在线购物平台同时拥有桌面端('desktop')和手机端('mobile')的应用程序。
这张表的主键是 (user_id, spend_date, platform)。
平台列 platform 是一种 ENUM ,类型为('desktop', 'mobile')。
 
写一段 SQL 来查找每天 仅 使用手机端用户、仅 使用桌面端用户和 同时 使用桌面端和手机端的用户人数和总支出金额。

查询结果格式如下例所示:

Spending table:

text
+---------+------------+----------+--------+
| user_id | spend_date | platform | amount |
+---------+------------+----------+--------+
| 1       | 2019-07-01 | mobile   | 100    |
| 1       | 2019-07-01 | desktop  | 100    |
| 2       | 2019-07-01 | mobile   | 100    |
| 2       | 2019-07-02 | mobile   | 100    |
| 3       | 2019-07-01 | desktop  | 100    |
| 3       | 2019-07-02 | desktop  | 100    |
+---------+------------+----------+--------+

Result table:

text
+------------+----------+--------------+-------------+
| spend_date | platform | total_amount | total_users |
+------------+----------+--------------+-------------+
| 2019-07-01 | desktop  | 100          | 1           |
| 2019-07-01 | mobile   | 100          | 1           |
| 2019-07-01 | both     | 200          | 1           |
| 2019-07-02 | desktop  | 100          | 1           |
| 2019-07-02 | mobile   | 100          | 1           |
| 2019-07-02 | both     | 0            | 0           |
+------------+----------+--------------+-------------+ 

在 2019-07-01, 用户1 同时 使用桌面端和手机端购买, 用户2 仅 使用了手机端购买,而用户3 仅 使用了桌面端购买。
在 2019-07-02, 用户2 仅 使用了手机端购买, 用户3 仅 使用了桌面端购买,且没有用户 同时 使用桌面端和手机端购买。

sql
-- 有点难度,难点一:按时间和id分组以及打标签,难点二:构建一张表来left join
思路分析
1.获取每一天的id的类型和acount
select 
spend_date,user_id,
if(count(distinct platform) =1,platform,'both') as platform,
sum(amount) as amount
from
Spending
group by spend_date, user_id

2.如果直接group by  spend_date, platform 就无法出现0,0的情况,考虑使用join来实现
构建表:
select distinct spend_date, "desktop" platform from Spending
union
select distinct spend_date, "mobile" platform from Spending
union
select distinct spend_date, "both" platform from Spending

综合:
select 
t1.spend_date,t1.platform,
ifnull(sum(amount),0)  as total_amount,
ifnull(count(distinct user_id),0) as total_users
from
(
select distinct spend_date, "desktop" platform from Spending
union
select distinct spend_date, "mobile" platform from Spending
union
select distinct spend_date, "both" platform from Spending
) t1
left join
( 
select 
spend_date,user_id,
if(count(distinct platform) =1,platform,"both") as platform,
sum(amount) as amount
from
Spending
group by spend_date, user_id
) t2
on t1.spend_date = t2.spend_date and t1.platform = t2.platform
group by t1.spend_date,t1.platform
sql
--摘评论区写法
select
    spend_date, platform,
    ifnull(sum(total_am),0) total_amount,
    ifnull(sum(total_u),0) total_users
from
(
    select p.spend_date, p.platform, t.total_am, t.total_u
    from
    (
        select distinct spend_date, "desktop" platform from Spending
        union
        select distinct spend_date, "mobile" platform from Spending
        union
        select distinct spend_date, "both" platform from Spending
    ) p
    left join
    (
        select spend_date, 
            if(count(distinct platform)=1, platform, 'both') plat,
            sum(amount) total_am,
            count(distinct user_id) total_u
        from Spending
        group by spend_date, user_id
    ) t
    on p.platform = t.plat and p.spend_date = t.spend_date
) temp
group by spend_date, platform

是否要对最外面的select 中的统计人数去重,不需要但是怎么和leedcode的执行答案有出入

62.报告的记录2(avg的应用)

编写一段 SQL 来查找:在被报告为垃圾广告的帖子中,被移除的帖子的每日平均占比,四舍五入到小数点后 2 位

动作表: Actions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| post_id       | int     |
| action_date   | date    |
| action        | enum    |
| extra         | varchar |
+---------------+---------+

这张表没有主键,并有可能存在重复的行。
action 列的类型是 ENUM,可能的值为 ('view', 'like', 'reaction', 'comment', 'report', 'share')。
extra 列拥有一些可选信息,例如:报告理由(a reason for report)或反应类型(a type of reaction)等。
移除表: Removals

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| post_id       | int     |
| remove_date   | date    | 
+---------------+---------+

这张表的主键是 post_id。
这张表的每一行表示一个被移除的帖子,原因可能是由于被举报或被管理员审查。
 

编写一段 SQL 来查找:在被报告为垃圾广告的帖子中,被移除的帖子的每日平均占比,四舍五入到小数点后 2 位。

查询结果的格式如下:

Actions table:

text
+---------+---------+-------------+--------+--------+
| user_id | post_id | action_date | action | extra  |
+---------+---------+-------------+--------+--------+
| 1       | 1       | 2019-07-01  | view   | null   |
| 1       | 1       | 2019-07-01  | like   | null   |
| 1       | 1       | 2019-07-01  | share  | null   |
| 2       | 2       | 2019-07-04  | view   | null   |
| 2       | 2       | 2019-07-04  | report | spam   |
| 3       | 4       | 2019-07-04  | view   | null   |
| 3       | 4       | 2019-07-04  | report | spam   |
| 4       | 3       | 2019-07-02  | view   | null   |
| 4       | 3       | 2019-07-02  | report | spam   |
| 5       | 2       | 2019-07-03  | view   | null   |
| 5       | 2       | 2019-07-03  | report | racism |
| 5       | 5       | 2019-07-03  | view   | null   |
| 5       | 5       | 2019-07-03  | report | racism |
+---------+---------+-------------+--------+--------+

Removals table:

text
+---------+-------------+
| post_id | remove_date |
+---------+-------------+
| 2       | 2019-07-20  |
| 3       | 2019-07-18  |
+---------+-------------+

Result table:

text
+-----------------------+
| average_daily_percent |
+-----------------------+
| 75.00                 |
+-----------------------+

2019-07-04 的垃圾广告移除率是 50%,因为有两张帖子被报告为垃圾广告,但只有一个得到移除。
2019-07-02 的垃圾广告移除率是 100%,因为有一张帖子被举报为垃圾广告并得到移除。
其余几天没有收到垃圾广告的举报,因此平均值为:(50 + 100) / 2 = 75%
注意,输出仅需要一个平均值即可,我们并不关注移除操作的日期。

sql
-- *100 位置不同影响结果....评论区提供了求平均值的方法比较好
select 
round(avg(s1),2)   as average_daily_percent
from 
(
select
action_date,
count(distinct Removals.post_id ) / count(distinct Actions.post_id) * 100 as s1
from
Actions 
left join 
Removals on Actions.post_id = Removals.post_id
where extra = "spam"
group by action_date
) t1
sql
SELECT
    ROUND(COUNT(DISTINCT R.post_id) / COUNT(DISTINCT A.post_id) * 100,2) average_daily_percent
FROM 
    Actions A
LEFT JOIN
    Removals R
ON A.post_id = R.post_id
WHERE
    extra='spam'

63.查询近三十天活跃用户数

sql
-- 简单题,我的写法,注意这里的近三十不是小于等于
select
activity_date as day ,count(distinct user_id) as active_users
from
Activity
where datediff("2019-07-27",activity_date ) < 30 and activity_date <= "2019-07-27"
group by activity_date

64.过去三十天的用户活动2

编写SQL查询以查找截至2019年7月27日(含)的30天内每个用户的平均会话数,四舍五入到小数点后两位。我们只统计那些会话期间用户至少进行一项活动的有效会话。

Table: Activity

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| session_id    | int     |
| activity_date | date    |
| activity_type | enum    |
+---------------+---------+

该表没有主键,它可能有重复的行。
activity_type 列是 ENUM(“ open_session”,“ end_session”,“ scroll_down”,“ send_message”)中的某一类型。
该表显示了社交媒体网站的用户活动。
请注意,每个会话完全属于一个用户。
 

编写SQL查询以查找截至2019年7月27日(含)的30天内每个用户的平均会话数,四舍五入到小数点后两位。我们只统计那些会话期间用户至少进行一项活动的有效会话。

 

查询结果格式如下例所示:

Activity table:

text
+---------+------------+---------------+---------------+
| user_id | session_id | activity_date | activity_type |
+---------+------------+---------------+---------------+
| 1       | 1          | 2019-07-20    | open_session  |
| 1       | 1          | 2019-07-20    | scroll_down   |
| 1       | 1          | 2019-07-20    | end_session   |
| 2       | 4          | 2019-07-20    | open_session  |
| 2       | 4          | 2019-07-21    | send_message  |
| 2       | 4          | 2019-07-21    | end_session   |
| 3       | 2          | 2019-07-21    | open_session  |
| 3       | 2          | 2019-07-21    | send_message  |
| 3       | 2          | 2019-07-21    | end_session   |
| 3       | 5          | 2019-07-21    | open_session  |
| 3       | 5          | 2019-07-21    | scroll_down   |
| 3       | 5          | 2019-07-21    | end_session   |
| 4       | 3          | 2019-06-25    | open_session  |
| 4       | 3          | 2019-06-25    | end_session   |
+---------+------------+---------------+---------------+

Result table:

text
+---------------------------+ 
| average_sessions_per_user |
+---------------------------+ 
| 1.33                      |
+---------------------------+ 

User 1 和 2 在过去30天内各自进行了1次会话,而用户3进行了2次会话,因此平均值为(1 +1 + 2)/ 3 = 1.33。

sql
--我的写法,麻烦了,看了评论区事实上直接求即可,就是上一题对avg的正确描述
select 
ifnull(round(sum(s1) /count(user_id),2),0) as  average_sessions_per_user
from 
(
select 
user_id,count(distinct session_id ) as s1
from 
Activity where datediff("2019-07-27",activity_date) < 30
and  
session_id 
in (
select
session_id
from
Activity
where datediff("2019-07-27",activity_date) < 30
group by session_id
having count(distinct activity_type) >= 1
) 
group by user_id
) t1
sql
select ifnull(round(count(distinct session_id)/count(distinct user_id),2),0) 
as average_sessions_per_user
from Activity
where activity_date between '2019-06-28' and '2019-07-27'

65.文章浏览1

sql
-- 简单题
select 
distinct author_id as id
from
Views
where author_id = viewer_id
order by id 

66.文章浏览2

编写一条 SQL 查询来找出在同一天阅读至少两篇文章的人,结果按照 id 升序排序。

Table: Views

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| article_id    | int     |
| author_id     | int     |
| viewer_id     | int     |
| view_date     | date    |
+---------------+---------+

此表无主键,因此可能会存在重复行。此表的每一行都表示某人在某天浏览了某位作者的某篇文章。 请注意,同一人的 author_id 和 viewer_id 是相同的。
 

编写一条 SQL 查询来找出在同一天阅读至少两篇文章的人,结果按照 id 升序排序。

查询结果的格式如下:

Views table:

text
+------------+-----------+-----------+------------+
| article_id | author_id | viewer_id | view_date  |
+------------+-----------+-----------+------------+
| 1          | 3         | 5         | 2019-08-01 |
| 3          | 4         | 5         | 2019-08-01 |
| 1          | 3         | 6         | 2019-08-02 |
| 2          | 7         | 7         | 2019-08-01 |
| 2          | 7         | 6         | 2019-08-02 |
| 4          | 7         | 1         | 2019-07-22 |
| 3          | 4         | 4         | 2019-07-21 |
| 3          | 4         | 4         | 2019-07-21 |
+------------+-----------+-----------+------------+

Result table:

text
+------+
| id   |
+------+
| 5    |
| 6    |
+------+
sql
-- 读题,跑了好几次,发现问题题目要求是读的文章,所以去重的字段应该是文章而不是读者
select  distinct viewer_id id
from views
group by viewer_id, view_date
having count(distinct article_id) > 1
order by id 

67.市场分析1

请写出一条SQL语句以查询每个用户的注册日期和在 2019 年作为买家的订单总数。

Table: Users

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| join_date      | date    |
| favorite_brand | varchar |
+----------------+---------+

此表主键是 user_id,表中描述了购物网站的用户信息,用户可以在此网站上进行商品买卖。
Table: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| item_id       | int     |
| buyer_id      | int     |
| seller_id     | int     |
+---------------+---------+

此表主键是 order_id,外键是 item_id 和(buyer_id,seller_id)。
Table: Item

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| item_id       | int     |
| item_brand    | varchar |
+---------------+---------+

此表主键是 item_id。
 
请写出一条SQL语句以查询每个用户的注册日期和在 2019 年作为买家的订单总数。

查询结果格式如下:

Users table:

text
+---------+------------+----------------+
| user_id | join_date  | favorite_brand |
+---------+------------+----------------+
| 1       | 2018-01-01 | Lenovo         |
| 2       | 2018-02-09 | Samsung        |
| 3       | 2018-01-19 | LG             |
| 4       | 2018-05-21 | HP             |
+---------+------------+----------------+

Orders table:

text
+----------+------------+---------+----------+-----------+
| order_id | order_date | item_id | buyer_id | seller_id |
+----------+------------+---------+----------+-----------+
| 1        | 2019-08-01 | 4       | 1        | 2         |
| 2        | 2018-08-02 | 2       | 1        | 3         |
| 3        | 2019-08-03 | 3       | 2        | 3         |
| 4        | 2018-08-04 | 1       | 4        | 2         |
| 5        | 2018-08-04 | 1       | 3        | 4         |
| 6        | 2019-08-05 | 2       | 2        | 4         |
+----------+------------+---------+----------+-----------+

Items table:

text
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1       | Samsung    |
| 2       | Lenovo     |
| 3       | LG         |
| 4       | HP         |
+---------+------------+

Result table:

text
+-----------+------------+----------------+
| buyer_id  | join_date  | orders_in_2019 |
+-----------+------------+----------------+
| 1         | 2018-01-01 | 1              |
| 2         | 2018-02-09 | 2              |
| 3         | 2018-01-19 | 0              |
| 4         | 2018-05-21 | 0              |
+-----------+------------+----------------+
sql
--我的写法,简单题
select 
user_id as buyer_id ,join_date ,ifnull(orders_in_2019,0) as orders_in_2019
from 
Users
left join 
( 
select
buyer_id,count(1) as orders_in_2019
from
Orders
where year(order_date) = "2019"
group by buyer_id
) t2
on Users. user_id = t2.buyer_id
sql
--注意错误的写法,where条件会把行给过滤掉,所以要条件提取到on上
select  u.user_id  ,u.join_date ,ifnull(count(o.order_id),0) orders_in_2019 
from  Users u 
left join Orders o 
on u.user_id=o.buyer_id 
where year(o.order_date)=2019
group by u.user_id

68.市场分析2

写一个 SQL 查询确定每一个用户按日期顺序卖出的第二件商品的品牌是否是他们最喜爱的品牌。如果一个用户卖出少于两件商品,查询的结果是 no 。

表: Users

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| join_date      | date    |
| favorite_brand | varchar |
+----------------+---------+

user_id 是该表的主键
表中包含一位在线购物网站用户的个人信息,用户可以在该网站出售和购买商品。
表: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| item_id       | int     |
| buyer_id      | int     |
| seller_id     | int     |
+---------------+---------+

order_id 是该表的主键
item_id 是 Items 表的外键
buyer_id 和 seller_id 是 Users 表的外键
表: Items

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| item_id       | int     |
| item_brand    | varchar |
+---------------+---------+

item_id 是该表的主键
 

写一个 SQL 查询确定每一个用户按日期顺序卖出的第二件商品的品牌是否是他们最喜爱的品牌。如果一个用户卖出少于两件商品,查询的结果是 no 。

题目保证没有一个用户在一天中卖出超过一件商品

下面是查询结果格式的例子:

Users table:

text
+---------+------------+----------------+
| user_id | join_date  | favorite_brand |
+---------+------------+----------------+
| 1       | 2019-01-01 | Lenovo         |
| 2       | 2019-02-09 | Samsung        |
| 3       | 2019-01-19 | LG             |
| 4       | 2019-05-21 | HP             |
+---------+------------+----------------+

Orders table:

text
+----------+------------+---------+----------+-----------+
| order_id | order_date | item_id | buyer_id | seller_id |
+----------+------------+---------+----------+-----------+
| 1        | 2019-08-01 | 4       | 1        | 2         |
| 2        | 2019-08-02 | 2       | 1        | 3         |
| 3        | 2019-08-03 | 3       | 2        | 3         |
| 4        | 2019-08-04 | 1       | 4        | 2         |
| 5        | 2019-08-04 | 1       | 3        | 4         |
| 6        | 2019-08-05 | 2       | 2        | 4         |
+----------+------------+---------+----------+-----------+

Items table:

text
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1       | Samsung    |
| 2       | Lenovo     |
| 3       | LG         |
| 4       | HP         |
+---------+------------+

Result table:

text
+-----------+--------------------+
| seller_id | 2nd_item_fav_brand |
+-----------+--------------------+
| 1         | no                 |
| 2         | yes                |
| 3         | yes                |
| 4         | no                 |
+-----------+--------------------+

id 为 1 的用户的查询结果是 no,因为他什么也没有卖出
id为 2 和 3 的用户的查询结果是 yes,因为他们卖出的第二件商品的品牌是他们自己最喜爱的品牌
id为 4 的用户的查询结果是 no,因为他卖出的第二件商品的品牌不是他最喜爱的品牌

sql
--我的写法,简单题注意'' 和"" 是使用
select 
user_id as seller_id,
case when favorite_brand = t3.item_brand then 'yes' else 'no' end as  "2nd_item_fav_brand"
from 
Users
left join 
(
select 
seller_id,item_brand
from 
(
select 
item_brand,seller_id,
row_number() over(partition by seller_id order by order_date ) as rn
from 
Orders
join Items on Orders.item_id = Items.item_id
) t1
where rn =2
) t3
on Users.user_id = t3.seller_id
order by seller_id
sql
-- 自连接获取第二个 having sum(o1.order_date > o2.order_date) = 1 学习一下
//使用sum()统计比当前订单日期更早的订单数,若为1,说明当前订单是对应用户卖
//出的第二单
select user_id seller_id, if(favorite_brand = item_brand, 'yes', 'no') 2nd_item_fav_brand
from users left join (
    select seller_id, item_brand
    from (
        select o1.seller_id, o1.item_id
        from orders o1 join orders o2
        on o1.seller_id = o2.seller_id
        group by o1.order_id
        having sum(o1.order_date > o2.order_date) = 1
    ) o join items i
    on o.item_id = i.item_id
) tmp
on user_id = seller_id

69.指定日期的产品价格

写一段 SQL来查找在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10。

产品数据表: Products

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| new_price     | int     |
| change_date   | date    |
+---------------+---------+

这张表的主键是 (product_id, change_date)。
这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。
 

写一段 SQL来查找在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10。

查询结果格式如下例所示:

Products table:

text
+------------+-----------+-------------+
| product_id | new_price | change_date |
+------------+-----------+-------------+
| 1          | 20        | 2019-08-14  |
| 2          | 50        | 2019-08-14  |
| 1          | 30        | 2019-08-15  |
| 1          | 35        | 2019-08-16  |
| 2          | 65        | 2019-08-17  |
| 3          | 20        | 2019-08-18  |
+------------+-----------+-------------+

Result table:

text
+------------+-------+
| product_id | price |
+------------+-------+
| 2          | 50    |
| 1          | 35    |
| 3          | 10    |
+------------+-------+
sql
-- 我的答案
select
t1.product_id,ifnull(t3.new_price,10) as price
from 
(
select
distinct product_id
from
Products
) t1
left join 
(
select
product_id,new_price
from 
Products
where (product_id,change_date) in 
(
select 
product_id,max(change_date)
from 
Products
where 
change_date <= '2019-08-16'
group by product_id
) 
) t3 
on t1.product_id = t3.product_id
sql
select distinct a.product_id,ifnull(b.new_price,10) as price 
from Products a left join 
(select*,row_number()over(partition by product_id order by change_date desc) as rk 
from Products where change_date<='2019-08-16' )b
on a.product_id=b.product_id and rk=1

distinct 联合去重的问题概念有点模糊?,说明上面的不去重的结果是每个id有多个相同的price,去重获取唯一一个,如果值不同使用,对id去重,且price也不相同,那么去重的结果是全部的值,要想获取全部的id值只能子查询获取

sql
-- 方案三,无需去重但是为什么比去重的跑得慢....
(select product_id as product_id,10 as price 
from Products 
group by product_id
having min(change_date)>'2019-08-16')
union all 
(select product_id,new_price as price 
from Products 
where (product_id,change_date) in
(select product_id,max(change_date) as max_date
from Products
where change_date<='2019-08-16'
group by product_id))

70.即时食物配送1

写一条 SQL 查询语句获取即时订单所占的百分比, 保留两位小数

配送表: Delivery

text
+-----------------------------+---------+
| Column Name                 | Type    |
+-----------------------------+---------+
| delivery_id                 | int     |
| customer_id                 | int     |
| order_date                  | date    |
| customer_pref_delivery_date | date    |
+-----------------------------+---------+

delivery_id 是表的主键。
该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。
 

如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

写一条 SQL 查询语句获取即时订单所占的百分比, 保留两位小数。

查询结果如下所示:

Delivery 表:

text
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1           | 1           | 2019-08-01 | 2019-08-02                  |
| 2           | 5           | 2019-08-02 | 2019-08-02                  |
| 3           | 1           | 2019-08-11 | 2019-08-11                  |
| 4           | 3           | 2019-08-24 | 2019-08-26                  |
| 5           | 4           | 2019-08-21 | 2019-08-22                  |
| 6           | 2           | 2019-08-11 | 2019-08-13                  |
+-------------+-------------+------------+-----------------------------+

Result 表:

text
+----------------------+
| immediate_percentage |
+----------------------+
| 33.33                |
+----------------------+

2 和 3 号订单为即时订单,其他的为计划订单

sql
select
round( count(if(order_date=customer_pref_delivery_date,1,null)) / count(1) *100,2) as immediate_percentage
from
Delivery
sql
select
round( sum(if(order_date=customer_pref_delivery_date,1,0)) / count(1) *100,2) as immediate_percentage
from
Delivery

效率问题,上两条SQL的效率

sql
--avg
select
round(avg(order_date=customer_pref_delivery_date)*100,2) immediate_percentage 
from
Delivery
sql
--自连接
SELECT ROUND(COUNT(d2.customer_pref_delivery_date)/COUNT(d1.delivery_id)*100,2)
AS immediate_percentage
FROM Delivery d1 LEFT JOIN Delivery d2
ON d1.delivery_id= d2.delivery_id 
AND d1.order_date= d2.customer_pref_delivery_date;

练习题 7

71.即时事物配送2

写一条 SQL 查询语句获取即时订单在所有用户的首次订单中的比例。保留两位小数。

配送表: Delivery

text
+-----------------------------+---------+
| Column Name                 | Type    |
+-----------------------------+---------+
| delivery_id                 | int     |
| customer_id                 | int     |
| order_date                  | date    |
| customer_pref_delivery_date | date    |
+-----------------------------+---------+

delivery_id 是表的主键。
该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。
 

如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

「首次订单」是顾客最早创建的订单。我们保证一个顾客只会有一个「首次订单」。

写一条 SQL 查询语句获取即时订单在所有用户的首次订单中的比例。保留两位小数。

 

查询结果如下所示:

Delivery 表:

text
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1           | 1           | 2019-08-01 | 2019-08-02                  |
| 2           | 2           | 2019-08-02 | 2019-08-02                  |
| 3           | 1           | 2019-08-11 | 2019-08-12                  |
| 4           | 3           | 2019-08-24 | 2019-08-24                  |
| 5           | 3           | 2019-08-21 | 2019-08-22                  |
| 6           | 2           | 2019-08-11 | 2019-08-13                  |
| 7           | 4           | 2019-08-09 | 2019-08-09                  |
+-------------+-------------+------------+-----------------------------+

Result 表:

text
+----------------------+
| immediate_percentage |
+----------------------+
| 50.00                |
+----------------------+

1 号顾客的 1 号订单是首次订单,并且是计划订单。
2 号顾客的 2 号订单是首次订单,并且是即时订单。
3 号顾客的 5 号订单是首次订单,并且是计划订单。
4 号顾客的 7 号订单是首次订单,并且是即时订单。
因此,一半顾客的首次订单是即时的

sql
--我的写法,考虑可能有的用户没有首次购买时间?,可以优化一下,把获取总的首次购买的总数直接count(1) 而不是用子查询获取

select 
round((count(1) / (select count(distinct customer_id) from Delivery)) *100,2) as immediate_percentage
from 
Delivery
where order_date = customer_pref_delivery_date
and (customer_id,order_date) in 
(
select
customer_id,min(order_date) as da
from
Delivery
group by customer_id
)
sql
select round(sum(order_date=customer_pref_delivery_date)/count(*)*100,2) immediate_percentage
from(
    select order_date,customer_pref_delivery_date,
           rank() over (partition by customer_id order by order_date) r
    from Delivery
) a
where r=1

72.重新格式化部门表

编写一个 SQL 查询来重新格式化表,使得新的表中有一个部门 id 列和一些对应 每个月 的收入(revenue)列。

部门表 Department:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| revenue       | int     |
| month         | varchar |
+---------------+---------+

(id, month) 是表的联合主键。
这个表格有关于每个部门每月收入的信息。
月份(month)可以取下列值 ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]。
 

编写一个 SQL 查询来重新格式化表,使得新的表中有一个部门 id 列和一些对应 每个月 的收入(revenue)列。

查询结果格式如下面的示例所示:

Department 表:

text
+------+---------+-------+
| id   | revenue | month |
+------+---------+-------+
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
+------+---------+-------+

查询得到的结果表:

text
+------+-------------+-------------+-------------+-----+-------------+
| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1    | 8000        | 7000        | 6000        | ... | null        |
| 2    | 9000        | null        | null        | ... | null        |
| 3    | null        | 10000       | null        | ... | null        |
+------+-------------+-------------+-------------+-----+-------------+

注意,结果表有 13 列 (1个部门 id 列 + 12个月份的收入列)。

sql
-- 简单题,考察group by 和聚合函数
select
id,
sum(if(month = "Jan",revenue,null)) as Jan_Revenue,
sum(if(month = "Feb",revenue,null)) as Feb_Revenue,
sum(if(month = "Mar",revenue,null)) as Mar_Revenue,
sum(if(month = "Apr",revenue,null)) as Apr_Revenue,
sum(if(month = "May",revenue,null)) as May_Revenue,
sum(if(month = "Jun",revenue,null)) as Jun_Revenue,
sum(if(month = "Jul",revenue,null)) as Jul_Revenue,
sum(if(month = "Aug",revenue,null)) as Aug_Revenue,
sum(if(month = "Sep",revenue,null)) as Sep_Revenue,
sum(if(month = "Oct",revenue,null)) as Oct_Revenue,
sum(if(month = "Nov",revenue,null)) as Nov_Revenue,
sum(if(month = "Dec",revenue,null)) as Dec_Revenue
from
Department
group by id
sql
select 
     id
    , sum(case `month` when 'Jan' then revenue else null end) as Jan_Revenue
    , sum(case `month` when 'Feb' then revenue else null end) as Feb_Revenue
    , sum(case `month` when 'Mar' then revenue else null end) as Mar_Revenue
    , sum(case `month` when 'Apr' then revenue else null end) as Apr_Revenue
    , sum(case `month` when 'May' then revenue else null end) as May_Revenue
    , sum(case `month` when 'Jun' then revenue else null end) as Jun_Revenue
    , sum(case `month` when 'Jul' then revenue else null end) as Jul_Revenue
    , sum(case `month` when 'Aug' then revenue else null end) as Aug_Revenue
    , sum(case `month` when 'Sep' then revenue else null end) as Sep_Revenue
    , sum(case `month` when 'Oct' then revenue else null end) as Oct_Revenue
    , sum(case `month` when 'Nov' then revenue else null end) as Nov_Revenue
    , sum(case `month` when 'Dec' then revenue else null end) as Dec_Revenue
from Department group by id

73.每月交易1

编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

Table: Transactions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| country       | varchar |
| state         | enum    |
| amount        | int     |
| trans_date    | date    |
+---------------+---------+

id 是这个表的主键。
该表包含有关传入事务的信息。
state 列类型为 “[”批准“,”拒绝“] 之一。
 

编写一个 sql 查询来查找每个月和每个国家/地区的事务数及其总金额、已批准的事务数及其总金额。

查询结果格式如下所示:

Transactions table:

text
+------+---------+----------+--------+------------+
| id   | country | state    | amount | trans_date |
+------+---------+----------+--------+------------+
| 121  | US      | approved | 1000   | 2018-12-18 |
| 122  | US      | declined | 2000   | 2018-12-19 |
| 123  | US      | approved | 2000   | 2019-01-01 |
| 124  | DE      | approved | 2000   | 2019-01-07 |
+------+---------+----------+--------+------------+

Result table:

text
+----------+---------+-------------+----------------+--------------------+-----------------------+
| month    | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
+----------+---------+-------------+----------------+--------------------+-----------------------+
| 2018-12  | US      | 2           | 1              | 3000               | 1000                  |
| 2019-01  | US      | 1           | 1              | 2000               | 2000                  |
| 2019-01  | DE      | 1           | 1              | 2000               | 2000                  |
+----------+---------+-------------+----------------+--------------------+-----------------------+
sql
-- 简单题,可以使用date_format或者left函数
select
substr(trans_date,1,7) month , country,count(state) trans_count,
sum(state = "approved") approved_count ,sum(amount) trans_total_amount,
sum(if(state = "approved",amount,0)) approved_total_amount
from
Transactions
group by country,substr(trans_date,1,7)
sql
select date_format(trans_date,"%Y-%m") month
,country,count(id) trans_count
,count(if(state<>"approved",null,state)) approved_count
,sum(amount) trans_total_amount
,sum(amount*(state<>"declined"))  approved_total_amount
from transactions 
group by date_format(trans_date,"%Y-%m"),country;

注意在group by之后使用count(字段=?) 统计的是全部的行,如果要过滤要使用case when 或者 if 来过滤例如:

text
count(if(state<>"approved",null,state)) approved_count

74.锦标赛优胜者

编写一个 SQL 查询来查找每组中的获胜者。

Players 玩家表

text
+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| player_id   | int   |
| group_id    | int   |
+-------------+-------+

player_id 是此表的主键。
此表的每一行表示每个玩家的组。
Matches 赛事表

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| match_id      | int     |
| first_player  | int     |
| second_player | int     | 
| first_score   | int     |
| second_score  | int     |
+---------------+---------+

match_id 是此表的主键。
每一行是一场比赛的记录,first_player 和 second_player 表示该场比赛的球员 ID。
first_score 和 second_score 分别表示 first_player 和 second_player 的得分。
你可以假设,在每一场比赛中,球员都属于同一组。
 

每组的获胜者是在组内累积得分最高的选手。如果平局,player_id 最小 的选手获胜。

编写一个 SQL 查询来查找每组中的获胜者。

查询结果格式如下所示

Players 表:

text
+-----------+------------+
| player_id | group_id   |
+-----------+------------+
| 15        | 1          |
| 25        | 1          |
| 30        | 1          |
| 45        | 1          |
| 10        | 2          |
| 35        | 2          |
| 50        | 2          |
| 20        | 3          |
| 40        | 3          |
+-----------+------------+

Matches 表:

text
+------------+--------------+---------------+-------------+--------------+
| match_id   | first_player | second_player | first_score | second_score |
+------------+--------------+---------------+-------------+--------------+
| 1          | 15           | 45            | 3           | 0            |
| 2          | 30           | 25            | 1           | 2            |
| 3          | 30           | 15            | 2           | 0            |
| 4          | 40           | 20            | 5           | 2            |
| 5          | 35           | 50            | 1           | 1            |
+------------+--------------+---------------+-------------+--------------+

Result 表:

text
+-----------+------------+
| group_id  | player_id  |
+-----------+------------+ 
| 1         | 15         |
| 2         | 35         |
| 3         | 40         |
+-----------+------------+
sql
--我的写法先获取每个人的分数,然后在组内比较获取最大值
select
group_id,player_id 
from 
(
select
group_id,player_id,row_number() over( partition by group_id order by score desc ,player_id asc ) as rn 
from 
Players
join 
(
select 
player,sum(score) as score
from 
(
select
first_player as player ,sum(first_score) as score
from
Matches
group by first_player
union all 
select 
second_player ,sum(second_score)
from
Matches
group by second_player
)
group by player
) t2
on Players.player_id = t2.player
) 
where rn =1
sql
-- 使用first_value可以减少嵌套一层select 
SELECT DISTINCT group_id,  
       FIRST_VALUE(player_id) OVER(PARTITION BY group_id ORDER BY score DESC, player_id) AS player_id
FROM
    (SELECT p.group_id,
            p.player_id,
            SUM(score)AS score
    FROM
        (SELECT first_player AS player_id, first_score AS score
        FROM Matches
        UNION ALL
        SELECT second_player AS player_id, second_score AS score
        FROM Matches) t1
    LEFT JOIN 
        Players p 
    ON t1.player_id = p.player_id
    GROUP BY player_id) t2
sql
-- 偷懒写法,group by 默认返回第一行
select group_id, player_id
from (
    select players.*, sum(if(player_id = first_player, first_score, second_score)) score
    from players join matches
    on player_id = first_player or player_id = second_player
    group by player_id
    order by score desc, player_id
) tmp
group by group_id

75.最后一个能进入电梯的人(自连接)

写一条 SQL 查询语句查找最后一个能进入电梯且不超过重量限制的 person_name 。题目确保队列中第一位的人可以进入电梯 。

表: Queue

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| person_id   | int     |
| person_name | varchar |
| weight      | int     |
| turn        | int     |
+-------------+---------+

person_id 是这个表的主键。
该表展示了所有等待电梯的人的信息。
表中 person_id 和 turn 列将包含从 1 到 n 的所有数字,其中 n 是表中的行数。
 

电梯最大载重量为 1000。

写一条 SQL 查询语句查找最后一个能进入电梯且不超过重量限制的 person_name 。题目确保队列中第一位的人可以进入电梯 。

查询结果如下所示 :

Queue 表

text
+-----------+-------------------+--------+------+
| person_id | person_name       | weight | turn |
+-----------+-------------------+--------+------+
| 5         | George Washington | 250    | 1    |
| 3         | John Adams        | 350    | 2    |
| 6         | Thomas Jefferson  | 400    | 3    |
| 2         | Will Johnliams    | 200    | 4    |
| 4         | Thomas Jefferson  | 175    | 5    |
| 1         | James Elephant    | 500    | 6    |
+-----------+-------------------+--------+------+

Result 表

text
+-------------------+
| person_name       |
+-------------------+
| Thomas Jefferson  |
+-------------------+

为了简化,Queue 表按 turn 列由小到大排序。
上例中 George Washington(id 5), John Adams(id 3) 和 Thomas Jefferson(id 6) 将可以进入电梯,因为他们的体重和为 250 + 350 + 400 = 1000。
Thomas Jefferson(id 6) 是最后一个体重合适并进入电梯的人。

sql
--我的写法,窗口写法
select 
person_name
from 
(
select
person_name,rank() over(order by weight_rn desc )  as rn 
from 
(
select
person_name,
sum(weight) over(order by turn ) as weight_rn  
from
Queue
) 
where weight_rn <= 1000
) 
where rn =1
sql
--自连接,where t1.turn >= t2.turn计算直到当前的总的质量
select t1.person_name
from queue t1, queue t2
where t1.turn >= t2.turn
group by t1.turn 
having sum(t2.weight) <= 1000
order by t1.turn desc
limit 1

76.每月交易2(tag)☆

编写一个 SQL 查询,以查找每个月和每个国家/地区的已批准交易的数量及其总金额、退单的数量及其总金额。
注意:在您的查询中,给定月份和国家,忽略所有为零的行。

Transactions 记录表

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| id             | int     |
| country        | varchar |
| state          | enum    |
| amount         | int     |
| trans_date     | date    |
+----------------+---------+

id 是这个表的主键。
该表包含有关传入事务的信息。
状态列是类型为 [approved(已批准)、declined(已拒绝)] 的枚举。
 

Chargebacks 表

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| trans_id       | int     |
| charge_date    | date    |
+----------------+---------+

退单包含有关放置在事务表中的某些事务的传入退单的基本信息。
trans_id 是 transactions 表的 id 列的外键。
每项退单都对应于之前进行的交易,即使未经批准。
 

编写一个 SQL 查询,以查找每个月和每个国家/地区的已批准交易的数量及其总金额、退单的数量及其总金额。

注意:在您的查询中,给定月份和国家,忽略所有为零的行。

查询结果格式如下所示:

Transactions 表:

text
+------+---------+----------+--------+------------+
| id   | country | state    | amount | trans_date |
+------+---------+----------+--------+------------+
| 101  | US      | approved | 1000   | 2019-05-18 |
| 102  | US      | declined | 2000   | 2019-05-19 |
| 103  | US      | approved | 3000   | 2019-06-10 |
| 104  | US      | declined | 4000   | 2019-06-13 |
| 105  | US      | approved | 5000   | 2019-06-15 |
+------+---------+----------+--------+------------+

Chargebacks 表:

text
+------------+------------+
| trans_id   | trans_date |
+------------+------------+
| 102        | 2019-05-29 |
| 101        | 2019-06-30 |
| 105        | 2019-09-18 |
+------------+------------+

Result 表:

text
+----------+---------+----------------+-----------------+-------------------+--------------------+
| month    | country | approved_count | approved_amount | chargeback_count  | chargeback_amount  |
+----------+---------+----------------+-----------------+-------------------+--------------------+
| 2019-05  | US      | 1              | 1000            | 1                 | 2000               |
| 2019-06  | US      | 2              | 8000            | 1                 | 1000               |
| 2019-09  | US      | 0              | 0               | 1                 | 5000               |
+----------+---------+----------------+-----------------+-------------------+------------------
sql
-- 总少了一个国家,我裂开了.....没有full join难受
select 
t1.dt as month ,t1.country,approved_count,approved_amount,chargeback_count,chargeback_amount
from 
(
select
country,left(trans_date,7) as dt ,ifnull(sum(state ="approved"),0) as approved_count,
ifnull(sum(if(state ="approved",amount,0)),0) as approved_amount
from
Transactions
group by country, left(trans_date,7)
) t1 
left   join 
(
select
country,left(Chargebacks.trans_date,7) as dt ,ifnull(count(1),0) as chargeback_count ,ifnull(sum(amount),0) as chargeback_amount
from 
Transactions
join Chargebacks on Transactions.id = Chargebacks.trans_id and left(Chargebacks.trans_date,7) = left( Transactions.trans_date,7)
group by country,left(Chargebacks.trans_date,7)
) t2
on t1.country = t2.country and t1.dt = t2.dt
sql
--学习使用tag用法,妙!!!!
select
    date_format(trans_date, '%Y-%m') as month,
    country,
    sum(if(state = 'approved',1,0)) as approved_count,
    sum(if(state = 'approved',amount,0)) as approved_amount,
    sum(if(state = 'chargeback',1,0)) as chargeback_count,
    sum(if(state = 'chargeback',amount,0)) as chargeback_amount
from
    (select
        *
    from
        transactions
    union all
    select
        trans_id as id,
        country,
        'chargeback' as state,
        amount,
        c.trans_date
    from
        chargebacks c left join transactions t 
        on t.id = c.trans_id) as temp
group by 1,2
having approved_count <> 0 or chargeback_count <> 0

防止为0

text
having approved_count <> 0 or chargeback_count <> 0

77.查询结果的质量与占比

编写一组 SQL 来查找每次查询的名称(query_name)、质量(quality) 和 劣质查询百分比(poor_query_percentage)。
质量(quality) 和劣质查询百分比(poor_query_percentage) 都应四舍五入到小数点后两位。

查询表 Queries: 

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| query_name  | varchar |
| result      | varchar |
| position    | int     |
| rating      | int     |
+-------------+---------+

此表没有主键,并可能有重复的行。
此表包含了一些从数据库中收集的查询信息。
“位置”(position)列的值为 1 到 500 。
“评分”(rating)列的值为 1 到 5 。评分小于 3 的查询被定义为质量很差的查询。
 

将查询结果的质量 quality 定义为:

各查询结果的评分与其位置之间比率的平均值。

将劣质查询百分比 poor_query_percentage 为:

评分小于 3 的查询结果占全部查询结果的百分比。

编写一组 SQL 来查找每次查询的名称(query_name)、质量(quality) 和 劣质查询百分比(poor_query_percentage)。

质量(quality) 和劣质查询百分比(poor_query_percentage) 都应四舍五入到小数点后两位。

查询结果格式如下所示:

Queries table:

text
+------------+-------------------+----------+--------+
| query_name | result            | position | rating |
+------------+-------------------+----------+--------+
| Dog        | Golden Retriever  | 1        | 5      |
| Dog        | German Shepherd   | 2        | 5      |
| Dog        | Mule              | 200      | 1      |
| Cat        | Shirazi           | 5        | 2      |
| Cat        | Siamese           | 3        | 3      |
| Cat        | Sphynx            | 7        | 4      |
+------------+-------------------+----------+--------+

Result table:

text
+------------+---------+-----------------------+
| query_name | quality | poor_query_percentage |
+------------+---------+-----------------------+
| Dog        | 2.50    | 33.33                 |
| Cat        | 0.66    | 33.33                 |
+------------+---------+-----------------------+

Dog 查询结果的质量为 ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50
Dog 查询结果的劣质查询百分比为 (1 / 3) * 100 = 33.33

Cat 查询结果的质量为 ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66
Cat 查询结果的劣质查询百分比为 (1 / 3) * 100 = 33.33

sql
--读懂题意,简单题
select 
query_name,round(sum(rating/position) /count(1),2) as quality,
round(sum(rating < 3) /count(1) *100 ,2)as poor_query_percentage
from
Queries
group by query_name
sql
SELECT 
    query_name, 
    ROUND(AVG(rating/position), 2) quality,
    ROUND(avg(rating < 3) * 100,2) poor_query_percentage
FROM Queries
GROUP BY query_name

78.查询球队积分

写出一条SQL语句以查询每个队的 team_id,team_name 和 num_points。结果根据 num_points 降序排序,如果有两队积分相同,那么这两队按 team_id  升序排序

Table: Teams

text
+---------------+----------+
| Column Name   | Type     |
+---------------+----------+
| team_id       | int      |
| team_name     | varchar  |
+---------------+----------+

此表的主键是 team_id,表中的每一行都代表一支独立足球队。
Table: Matches

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| match_id      | int     |
| host_team     | int     |
| guest_team    | int     | 
| host_goals    | int     |
| guest_goals   | int     |
+---------------+---------+

此表的主键是 match_id,表中的每一行都代表一场已结束的比赛,比赛的主客队分别由它们自己的 id 表示,他们的进球由 host_goals 和 guest_goals 分别表示。
 

积分规则如下:

赢一场得三分;
平一场得一分;
输一场不得分。
写出一条SQL语句以查询每个队的 team_id,team_name 和 num_points。结果根据 num_points 降序排序,如果有两队积分相同,那么这两队按 team_id  升序排序。

查询结果格式如下:

Teams table:

text
+-----------+--------------+
| team_id   | team_name    |
+-----------+--------------+
| 10        | Leetcode FC  |
| 20        | NewYork FC   |
| 30        | Atlanta FC   |
| 40        | Chicago FC   |
| 50        | Toronto FC   |
+-----------+--------------+

Matches table:

text
+------------+--------------+---------------+-------------+--------------+
| match_id   | host_team    | guest_team    | host_goals  | guest_goals  |
+------------+--------------+---------------+-------------+--------------+
| 1          | 10           | 20            | 3           | 0            |
| 2          | 30           | 10            | 2           | 2            |
| 3          | 10           | 50            | 5           | 1            |
| 4          | 20           | 30            | 1           | 0            |
| 5          | 50           | 30            | 1           | 0            |
+------------+--------------+---------------+-------------+--------------+

Result table:

text
+------------+--------------+---------------+
| team_id    | team_name    | num_points    |
+------------+--------------+---------------+
| 10         | Leetcode FC  | 7             |
| 20         | NewYork FC   | 3             |
| 50         | Toronto FC   | 3             |
| 30         | Atlanta FC   | 1             |
| 40         | Chicago FC   | 0             |
+------------+--------------+---------------+
sql
--我的写法,读懂题意
select
Teams.team_id team_id,team_name, ifnull(num_points,0) as num_points 
from 
Teams left join 
(
select 
team_id,sum(points) as num_points 
from 
(
select 
host_team as team_id,sum(case when host_goals > guest_goals  then 3 when host_goals < guest_goals then 0 else 1 end ) as points 
from
Matches
group by host_team
union all 
select 
guest_team  ,sum(case when host_goals > guest_goals  then 0 when host_goals < guest_goals then 3 else 1 end ) 
from
Matches
group by guest_team 
) t1
group by  team_id
) t2 
on Teams.team_id = t2.team_id
order by num_points desc  ,team_id 
sql
--评论区写法
select t.team_id,t.team_name,
        ifnull(sum(case when m.host_goals>m.guest_goals and t.team_id=m.host_team then 3 
                        when m.host_goals=m.guest_goals and t.team_id=m.host_team then 1
                        when m.host_goals<m.guest_goals and t.team_id=m.host_team then 0
                        when m.host_goals>m.guest_goals and t.team_id=m.guest_team then 0
                        when m.host_goals=m.guest_goals and t.team_id=m.guest_team then 1
                        when m.host_goals<m.guest_goals and t.team_id=m.guest_team then 3
                   end),0) as num_points
from Teams t,Matches m
group by t.team_id
order by num_points desc,t.team_id asc

79.报告系统状态的连续日期

编写一个 SQL 查询 2019-01-01 到 2019-12-31 期间任务连续同状态 period_state 的起止日期(start_date 和 end_date)。即如果任务失败了,就是失败状态的起止日期,如果任务成功了,就是成功状态的起止日期。

Table: Failed

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| fail_date    | date    |
+--------------+---------+

该表主键为 fail_date。
该表包含失败任务的天数.
Table: Succeeded

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| success_date | date    |
+--------------+---------+

该表主键为 success_date。
该表包含成功任务的天数.
 

系统 每天 运行一个任务。每个任务都独立于先前的任务。任务的状态可以是失败或是成功。

编写一个 SQL 查询 2019-01-01 到 2019-12-31 期间任务连续同状态 period_state 的起止日期(start_date 和 end_date)。即如果任务失败了,就是失败状态的起止日期,如果任务成功了,就是成功状态的起止日期。

最后结果按照起始日期 start_date 排序

查询结果样例如下所示:

Failed table:

text
+-------------------+
| fail_date         |
+-------------------+
| 2018-12-28        |
| 2018-12-29        |
| 2019-01-04        |
| 2019-01-05        |
+-------------------+

Succeeded table:

text
+-------------------+
| success_date      |
+-------------------+
| 2018-12-30        |
| 2018-12-31        |
| 2019-01-01        |
| 2019-01-02        |
| 2019-01-03        |
| 2019-01-06        |
+-------------------+

Result table:

text
+--------------+--------------+--------------+
| period_state | start_date   | end_date     |
+--------------+--------------+--------------+
| succeeded    | 2019-01-01   | 2019-01-03   |
| failed       | 2019-01-04   | 2019-01-05   |
| succeeded    | 2019-01-06   | 2019-01-06   |
+--------------+--------------+--------------+

结果忽略了 2018 年的记录,因为我们只关心从 2019-01-01 到 2019-12-31 的记录
从 2019-01-01 到 2019-01-03 所有任务成功,系统状态为 "succeeded"。
从 2019-01-04 到 2019-01-05 所有任务失败,系统状态为 "failed"。
从 2019-01-06 到 2019-01-06 所有任务成功,系统状态为 "succeeded"。

sql
--终于跑对了,Oracle真麻烦
select
'succeeded' as period_state ,to_char(min(success_date),'yyyy-mm-dd') as start_date,
to_char(max(success_date),'yyyy-mm-dd') as end_date
from 
(
select
success_date,
(success_date - row_number() over(order by success_date) ) rn 
from
Succeeded
where to_char(success_date,'yyyy-mm-dd') >= '2019-01-01'  and to_char(success_date,'yyyy-mm-dd') <=  '2019-12-31'
)
group by rn 
union all 
select
'failed',to_char(min(fail_date),'yyyy-mm-dd'),to_char(max(fail_date),'yyyy-mm-dd')
from 
(
select
fail_date,
( fail_date   - row_number() over(order by  fail_date  ) ) rn 
from
Failed
where to_char(fail_date,'yyyy-mm-dd') between '2019-01-01'  and  '2019-12-31'
) 
group by rn 
order by start_date
sql
-- 整体求,注意不要排序简单的连续登陆案例变形题
select state as period_state,min(dt) as start_date,max(dt) as end_date 
from
(
    select *,subdate(dt,rank() over(partition by state order by dt)) as dif 
    from
    (
        select 'failed' as state,fail_date as dt from failed where fail_date between '2019-01-01' and '2019-12-31'
    union all
        select 'succeeded' as state,success_date as dt from succeeded where success_date between '2019-01-01' and '2019-12-31'
     )t1 
)t2
group by state,dif
order by dt

80.每个帖子的评论数

编写 SQL 语句以查找每个帖子的评论数。
结果表应包含帖子的 post_id 和对应的评论数 number_of_comments 并且按 post_id 升序排列。
Submissions 可能包含重复的评论。您应该计算每个帖子的唯一评论数。
Submissions 可能包含重复的帖子。您应该将它们视为一个帖子。

表 Submissions 结构如下:

text
+---------------+----------+
| 列名           | 类型     |
+---------------+----------+
| sub_id        | int      |
| parent_id     | int      |
+---------------+----------+

上表没有主键, 所以可能会出现重复的行。
每行可以是一个帖子或对该帖子的评论。
如果是帖子的话,parent_id 就是 null。
对于评论来说,parent_id 就是表中对应帖子的 sub_id。
 

编写 SQL 语句以查找每个帖子的评论数。

结果表应包含帖子的 post_id 和对应的评论数 number_of_comments 并且按 post_id 升序排列。

Submissions 可能包含重复的评论。您应该计算每个帖子的唯一评论数。

Submissions 可能包含重复的帖子。您应该将它们视为一个帖子。

查询结果格式如下例所示:

Submissions table:

text
+---------+------------+
| sub_id  | parent_id  |
+---------+------------+
| 1       | Null       |
| 2       | Null       |
| 1       | Null       |
| 12      | Null       |
| 3       | 1          |
| 5       | 2          |
| 3       | 1          |
| 4       | 1          |
| 9       | 1          |
| 10      | 2          |
| 6       | 7          |
+---------+------------+

结果表:

text
+---------+--------------------+
| post_id | number_of_comments |
+---------+--------------------+
| 1       | 3                  |
| 2       | 2                  |
| 12      | 0                  |
+---------+--------------------+

表中 ID 为 1 的帖子有 ID 为 3、4 和 9 的三个评论。表中 ID 为 3 的评论重复出现了,所以我们只对它进行了一次计数。
表中 ID 为 2 的帖子有 ID 为 5 和 10 的两个评论。
ID 为 12 的帖子在表中没有评论。
表中 ID 为 6 的评论是对 ID 为 7 的已删除帖子的评论,因此我们将其忽略。

sql
-- 简单题
select
a.sub_id as post_id ,ifnull(count(distinct b.sub_id ),0) as  number_of_comments
from 
(
select
distinct sub_id as sub_id
from
Submissions
where parent_id is null
) a 
left join 
Submissions b
on a.sub_id = b.parent_id
group by a.sub_id
sql
select s1.sub_id post_id, count(distinct s2.sub_id) number_of_comments
from 
submissions s1 left join submissions s2 on s1.sub_id = s2.parent_id
where s1.parent_id is null
group by s1.sub_id
order by 1

一个基础题left join on 和 left join where 的区别,left join on 无论是否满足都会返回左边的数据

https://www.cnblogs.com/leochenliang/p/7364665.html

练习题 8

81.平均售价

编写SQL查询以查找每种产品的平均售价。
average_price 应该四舍五入到小数点后两位。

Table: Prices

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| start_date    | date    |
| end_date      | date    |
| price         | int     |
+---------------+---------+

(product_id,start_date,end_date) 是 Prices 表的主键。
Prices 表的每一行表示的是某个产品在一段时期内的价格。
每个产品的对应时间段是不会重叠的,这也意味着同一个产品的价格时段不会出现交叉。
 

Table: UnitsSold

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| purchase_date | date    |
| units         | int     |
+---------------+---------+

UnitsSold 表没有主键,它可能包含重复项。
UnitsSold 表的每一行表示的是每种产品的出售日期,单位和产品 id。
 

编写SQL查询以查找每种产品的平均售价。
average_price 应该四舍五入到小数点后两位。
查询结果格式如下例所示:

Prices table:

text
+------------+------------+------------+--------+
| product_id | start_date | end_date   | price  |
+------------+------------+------------+--------+
| 1          | 2019-02-17 | 2019-02-28 | 5      |
| 1          | 2019-03-01 | 2019-03-22 | 20     |
| 2          | 2019-02-01 | 2019-02-20 | 15     |
| 2          | 2019-02-21 | 2019-03-31 | 30     |
+------------+------------+------------+--------+

UnitsSold table:

text
+------------+---------------+-------+
| product_id | purchase_date | units |
+------------+---------------+-------+
| 1          | 2019-02-25    | 100   |
| 1          | 2019-03-01    | 15    |
| 2          | 2019-02-10    | 200   |
| 2          | 2019-03-22    | 30    |
+------------+---------------+-------+

Result table:

text
+------------+---------------+
| product_id | average_price |
+------------+---------------+
| 1          | 6.96          |
| 2          | 16.96         |
+------------+---------------+

平均售价 = 产品总价 / 销售的产品数量。
产品 1 的平均售价 = ((100 * 5)+(15 * 20) )/ 115 = 6.96
产品 2 的平均售价 = ((200 * 15)+(30 * 30) )/ 230 = 16.96

sql
--简单题,我的写法
select
t1.product_id product_id,ifnull(round(sum(price*units) / sum(units),2),0) average_price
from
Prices t1
left join
UnitsSold t2
on t1.product_id = t2.product_id and purchase_date between start_date and end_date
group by t1.product_id

82.页面推荐

写一段 SQL 向user_id = 1 的用户,推荐其朋友们喜欢的页面。不要推荐该用户已经喜欢的页面。

朋友关系列表: Friendship

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user1_id      | int     |
| user2_id      | int     |
+---------------+---------+

这张表的主键是 (user1_id, user2_id)。
这张表的每一行代表着 user1_id 和 user2_id 之间存在着朋友关系。
 

喜欢列表: Likes

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| page_id     | int     |
+-------------+---------+

这张表的主键是 (user_id, page_id)。
这张表的每一行代表着 user_id 喜欢 page_id。
 

写一段 SQL  向user_id = 1 的用户,推荐其朋友们喜欢的页面。不要推荐该用户已经喜欢的页面。

你返回的结果中不应当包含重复项。

返回结果的格式如下例所示:

Friendship table:

text
+----------+----------+
| user1_id | user2_id |
+----------+----------+
| 1        | 2        |
| 1        | 3        |
| 1        | 4        |
| 2        | 3        |
| 2        | 4        |
| 2        | 5        |
| 6        | 1        |
+----------+----------+

Likes table:

text
+---------+---------+
| user_id | page_id |
+---------+---------+
| 1       | 88      |
| 2       | 23      |
| 3       | 24      |
| 4       | 56      |
| 5       | 11      |
| 6       | 33      |
| 2       | 77      |
| 3       | 77      |
| 6       | 88      |
+---------+---------+

Result table:

text
+------------------+
| recommended_page |
+------------------+
| 23               |
| 24               |
| 56               |
| 33               |
| 77               |
+------------------+

用户1 同 用户2, 3, 4, 6 是朋友关系。
推荐页面为: 页面23 来自于 用户2, 页面24 来自于 用户3, 页面56 来自于 用户3 以及 页面33 来自于 用户6。
页面77 同时被 用户2 和 用户3 推荐。
页面88 没有被推荐,因为 用户1 已经喜欢了它。

sql
--简单题我的写法,使用union all  代替 union 提高速度,在外层来去重
select
distinct page_id as recommended_page
from 
Likes
join 
(
select
user2_id as user1_f
from
Friendship
where user1_id = 1
union 
select
user1_id
from
Friendship
where user2_id = 1
) t1 
on Likes.user_id = t1.user1_f
where page_id not in (select page_id from Likes where user_id =1 )

83.向公司CEO汇报的所有人

用 SQL 查询出所有直接或间接向公司 CEO 汇报工作的职工的 employee_id 。

员工表:Employees

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| employee_id   | int     |
| employee_name | varchar |
| manager_id    | int     |
+---------------+---------+

employee_id 是这个表的主键。
这个表中每一行中,employee_id 表示职工的 ID,employee_name 表示职工的名字,manager_id 表示该职工汇报工作的直线经理。
这个公司 CEO 是 employee_id = 1 的人。
 

用 SQL 查询出所有直接或间接向公司 CEO 汇报工作的职工的 employee_id 。

由于公司规模较小,经理之间的间接关系不超过 3 个经理。

可以以任何顺序返回的结果,不需要去重。

查询结果示例如下:

Employees table:

text
+-------------+---------------+------------+
| employee_id | employee_name | manager_id |
+-------------+---------------+------------+
| 1           | Boss          | 1          |
| 3           | Alice         | 3          |
| 2           | Bob           | 1          |
| 4           | Daniel        | 2          |
| 7           | Luis          | 4          |
| 8           | Jhon          | 3          |
| 9           | Angela        | 8          |
| 77          | Robert        | 1          |
+-------------+---------------+------------+

Result table:

text
+-------------+
| employee_id |
+-------------+
| 2           |
| 77          |
| 4           |
| 7           |
+-------------+

公司 CEO 的 employee_id 是 1.
employee_id 是 2 和 77 的职员直接汇报给公司 CEO。
employee_id 是 4 的职员间接汇报给公司 CEO 4 --> 2 --> 1 。
employee_id 是 7 的职员间接汇报给公司 CEO 7 --> 4 --> 2 --> 1 。
employee_id 是 3, 8 ,9 的职员不会直接或间接的汇报给公司 CEO。

sql
--简单题,我的写法读懂题意,注意or要打括号
select
a.employee_id as employee_id
from
Employees a
left join Employees b on a.manager_id = b.employee_id
left join Employees c on b.manager_id = c.employee_id
left join Employees d on c.manager_id = d.employee_id
where (b.manager_id =1 or c.manager_id =1 or d.manager_id =1 ) and a.employee_id != 1
sql
-- 考虑如果第二个就是1的话与第三张表连接一定是1-1所以成立
select distinct
    E1.employee_id
from Employees E1, Employees E2, Employees E3
where E1.manager_id = E2.employee_id
and E2.manager_id = E3.employee_id
and E1.employee_id != 1 
and E3.manager_id = 1;

84.学生参加各科的测试次数

要求写一段 SQL 语句,查询出每个学生参加每一门科目测试的次数,结果按 student_id 和 subject_name 排序。

学生表: Students

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| student_name  | varchar |
+---------------+---------+

主键为 student_id(学生ID),该表内的每一行都记录有学校一名学生的信息。
 

科目表: Subjects

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| subject_name | varchar |
+--------------+---------+

主键为 subject_name(科目名称),每一行记录学校的一门科目名称。
 

考试表: Examinations

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| student_id   | int     |
| subject_name | varchar |
+--------------+---------+

这张表压根没有主键,可能会有重复行。
学生表里的一个学生修读科目表里的每一门科目,而这张考试表的每一行记录就表示学生表里的某个学生参加了一次科目表里某门科目的测试。
 

要求写一段 SQL 语句,查询出每个学生参加每一门科目测试的次数,结果按 student_id 和 subject_name 排序。

查询结构格式如下所示:

Students table:

text
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1          | Alice        |
| 2          | Bob          |
| 13         | John         |
| 6          | Alex         |
+------------+--------------+

Subjects table:

text
+--------------+
| subject_name |
+--------------+
| Math         |
| Physics      |
| Programming  |
+--------------+

Examinations table:

text
+------------+--------------+
| student_id | subject_name |
+------------+--------------+
| 1          | Math         |
| 1          | Physics      |
| 1          | Programming  |
| 2          | Programming  |
| 1          | Physics      |
| 1          | Math         |
| 13         | Math         |
| 13         | Programming  |
| 13         | Physics      |
| 2          | Math         |
| 1          | Math         |
+------------+--------------+

Result table:

text
+------------+--------------+--------------+----------------+
| student_id | student_name | subject_name | attended_exams |
+------------+--------------+--------------+----------------+
| 1          | Alice        | Math         | 3              |
| 1          | Alice        | Physics      | 2              |
| 1          | Alice        | Programming  | 1              |
| 2          | Bob          | Math         | 1              |
| 2          | Bob          | Physics      | 0              |
| 2          | Bob          | Programming  | 1              |
| 6          | Alex         | Math         | 0              |
| 6          | Alex         | Physics      | 0              |
| 6          | Alex         | Programming  | 0              |
| 13         | John         | Math         | 1              |
| 13         | John         | Physics      | 1              |
| 13         | John         | Programming  | 1              |
+------------+--------------+--------------+----------------+

结果表需包含所有学生和所有科目(即便测试次数为0):
Alice 参加了 3 次数学测试, 2 次物理测试,以及 1 次编程测试;
Bob 参加了 1 次数学测试, 1 次编程测试,没有参加物理测试;
Alex 啥测试都没参加;
John 参加了数学、物理、编程测试各 1 次

sql
--有点坑,简单题要借助第三张表来实现
-- 直接count(t2.subject_name)  attended_exams 不用ifnull
select
t1.student_id,max(t1.student_name) student_name ,t1.subject_name,
ifnull(sum(if(t2.subject_name is not null,1,0)),0)  attended_exams
from 
(
select
student_id,student_name,subject_name
from 
Students
cross join Subjects
) t1 
left join 
Examinations t2 on t1.student_id = t2.student_id and t1.subject_name = t2.subject_name
group by t1.student_id,t1.subject_name
order by t1.student_id,subject_name

85.找到连续区间的开始和结束数字

后来一些 ID 从 Logs 表中删除。编写一个 SQL 查询得到 Logs 表中的连续区间的开始数字和结束数字。

表:Logs

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| log_id        | int     |
+---------------+---------+

id 是上表的主键。
上表的每一行包含日志表中的一个 ID。
 

后来一些 ID 从 Logs 表中删除。编写一个 SQL 查询得到 Logs 表中的连续区间的开始数字和结束数字。

将查询表按照 start_id 排序。

查询结果格式如下面的例子:

Logs 表:

text
+------------+
| log_id     |
+------------+
| 1          |
| 2          |
| 3          |
| 7          |
| 8          |
| 10         |
+------------+

结果表:

text
+------------+--------------+
| start_id   | end_id       |
+------------+--------------+
| 1          | 3            |
| 7          | 8            |
| 10         | 10           |
+------------+--------------+

结果表应包含 Logs 表中的所有区间。
从 1 到 3 在表中。
从 4 到 6 不在表中。
从 7 到 8 在表中。
9 不在表中。
10 在表中。

sql
--简单题,窗口写法
select
min(log_id) start_id  ,max(log_id) end_id    
from 
(
select
log_id,
(log_id - row_number() over(order by log_id) ) as rn 
from
Logs
) t1
group by rn 
order by start_id
sql
select a.log_id as START_ID ,min(b.log_id) as END_ID from 
(select log_id from logs where log_id-1 not in (select * from logs)) a,
(select log_id from logs where log_id+1 not in (select * from logs)) b
where b.log_id>=a.log_id
group by a.log_id

86.不同国家的天气类型

写一段 SQL 来找到表中每个国家在 2019 年 11 月的天气类型
天气类型的定义如下:当 weather_state 的平均值小于或等于15返回 Cold,当 weather_state 的平均值大于或等于 25 返回 Hot,否则返回 Warm。

国家表:Countries

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| country_id    | int     |
| country_name  | varchar |
+---------------+---------+

country_id 是这张表的主键。
该表的每行有 country_id 和 country_name 两列。
 

天气表:Weather

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| country_id    | int     |
| weather_state | varchar |
| day           | date    |
+---------------+---------+

(country_id, day) 是该表的复合主键。
该表的每一行记录了某个国家某一天的天气情况。
 

写一段 SQL 来找到表中每个国家在 2019 年 11 月的天气类型。

天气类型的定义如下:当 weather_state 的平均值小于或等于15返回 Cold,当 weather_state 的平均值大于或等于 25 返回 Hot,否则返回 Warm。

你可以以任意顺序返回你的查询结果。

查询结果格式如下所示:

Countries table:

text
+------------+--------------+
| country_id | country_name |
+------------+--------------+
| 2          | USA          |
| 3          | Australia    |
| 7          | Peru         |
| 5          | China        |
| 8          | Morocco      |
| 9          | Spain        |
+------------+--------------+

Weather table:

text
+------------+---------------+------------+
| country_id | weather_state | day        |
+------------+---------------+------------+
| 2          | 15            | 2019-11-01 |
| 2          | 12            | 2019-10-28 |
| 2          | 12            | 2019-10-27 |
| 3          | -2            | 2019-11-10 |
| 3          | 0             | 2019-11-11 |
| 3          | 3             | 2019-11-12 |
| 5          | 16            | 2019-11-07 |
| 5          | 18            | 2019-11-09 |
| 5          | 21            | 2019-11-23 |
| 7          | 25            | 2019-11-28 |
| 7          | 22            | 2019-12-01 |
| 7          | 20            | 2019-12-02 |
| 8          | 25            | 2019-11-05 |
| 8          | 27            | 2019-11-15 |
| 8          | 31            | 2019-11-25 |
| 9          | 7             | 2019-10-23 |
| 9          | 3             | 2019-12-23 |
+------------+---------------+------------+

Result table:

text
+--------------+--------------+
| country_name | weather_type |
+--------------+--------------+
| USA          | Cold         |
| Austraila    | Cold         |
| Peru         | Hot          |
| China        | Warm         |
| Morocco      | Hot          |
+--------------+--------------+

USA 11 月的平均 weather_state 为 (15) / 1 = 15 所以天气类型为 Cold。
Australia 11 月的平均 weather_state 为 (-2 + 0 + 3) / 3 = 0.333 所以天气类型为 Cold。
Peru 11 月的平均 weather_state 为 (25) / 1 = 25 所以天气类型为 Hot。
China 11 月的平均 weather_state 为 (16 + 18 + 21) / 3 = 18.333 所以天气类型为 Warm。
Morocco 11 月的平均 weather_state 为 (25 + 27 + 31) / 3 = 27.667 所以天气类型为 Hot。
我们并不知道 Spain 在 11 月的 weather_state 情况所以无需将他包含在结果中。

sql
--简单题,mysql使用left老忘记,date_format(w.day,'%Y-%m')='2019-11'也行
select 
country_name,case when s1 <= 15 then 'Cold' when s1>= 25 then 'Hot' else 'Warm' end  weather_type
from 
Countries join 
(
select 
country_id,avg(weather_state) as s1
from 
Weather
where to_char(day,'yyyy-mm') = '2019-11'
group by country_id,to_char(day,'yyyy-mm')
) t1
on Countries.country_id = t1.country_id

87.团队人数

编写一个 SQL 查询,以求得每个员工所在团队的总人数

员工表:Employee

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| employee_id   | int     |
| team_id       | int     |
+---------------+---------+

employee_id 字段是这张表的主键,表中的每一行都包含每个员工的 ID 和他们所属的团队。
编写一个 SQL 查询,以求得每个员工所在团队的总人数。

查询结果中的顺序无特定要求。

查询结果格式示例如下:

Employee Table:

text
+-------------+------------+
| employee_id | team_id    |
+-------------+------------+
|     1       |     8      |
|     2       |     8      |
|     3       |     8      |
|     4       |     7      |
|     5       |     9      |
|     6       |     9      |
+-------------+------------+

Result table:

text
+-------------+------------+
| employee_id | team_size  |
+-------------+------------+
|     1       |     3      |
|     2       |     3      |
|     3       |     3      |
|     4       |     1      |
|     5       |     2      |
|     6       |     2      |
+-------------+------------+

ID 为 1、2、3 的员工是 team_id 为 8 的团队的成员,
ID 为 4 的员工是 team_id 为 7 的团队的成员,
ID 为 5、6 的员工是 team_id 为 9 的团队的成员。

sql
-- 简单题,我的写法
select
employee_id,team_size
from
Employee t1 
join 
(
select
team_id,count(employee_id) team_size
from
Employee
group by team_id
) t2 
on t1.team_id = t2.team_id
sql
select employee_id, count(*) over(partition by team_id) as team_size
from employee

88.不同性别每日分数统计

写一条SQL语句查询每种性别在每一天的总分,并按性别和日期对查询结果排序

表: Scores

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| player_name   | varchar |
| gender        | varchar |
| day           | date    |
| score_points  | int     |
+---------------+---------+

(gender, day)是该表的主键
一场比赛是在女队和男队之间举行的
该表的每一行表示一个名叫 (player_name) 性别为 (gender) 的参赛者在某一天获得了 (score_points) 的分数
如果参赛者是女性,那么 gender 列为 'F',如果参赛者是男性,那么 gender 列为 'M'
 

写一条SQL语句查询每种性别在每一天的总分,并按性别和日期对查询结果排序

下面是查询结果格式的例子:

Scores表:

text
+-------------+--------+------------+--------------+
| player_name | gender | day        | score_points |
+-------------+--------+------------+--------------+
| Aron        | F      | 2020-01-01 | 17           |
| Alice       | F      | 2020-01-07 | 23           |
| Bajrang     | M      | 2020-01-07 | 7            |
| Khali       | M      | 2019-12-25 | 11           |
| Slaman      | M      | 2019-12-30 | 13           |
| Joe         | M      | 2019-12-31 | 3            |
| Jose        | M      | 2019-12-18 | 2            |
| Priya       | F      | 2019-12-31 | 23           |
| Priyanka    | F      | 2019-12-30 | 17           |
+-------------+--------+------------+--------------+

结果表:

text
+--------+------------+-------+
| gender | day        | total |
+--------+------------+-------+
| F      | 2019-12-30 | 17    |
| F      | 2019-12-31 | 40    |
| F      | 2020-01-01 | 57    |
| F      | 2020-01-07 | 80    |
| M      | 2019-12-18 | 2     |
| M      | 2019-12-25 | 13    |
| M      | 2019-12-30 | 26    |
| M      | 2019-12-31 | 29    |
| M      | 2020-01-07 | 36    |
+--------+------------+-------+

女性队伍:
第一天是 2019-12-30,Priyanka 获得 17 分,队伍的总分是 17 分
第二天是 2019-12-31, Priya 获得 23 分,队伍的总分是 40 分
第三天是 2020-01-01, Aron 获得 17 分,队伍的总分是 57 分
第四天是 2020-01-07, Alice 获得 23 分,队伍的总分是 80 分
男性队伍:
第一天是 2019-12-18, Jose 获得 2 分,队伍的总分是 2 分
第二天是 2019-12-25, Khali 获得 11 分,队伍的总分是 13 分
第三天是 2019-12-30, Slaman 获得 13 分,队伍的总分是 26 分
第四天是 2019-12-31, Joe 获得 3 分,队伍的总分是 29 分
第五天是 2020-01-07, Bajrang 获得 7 分,队伍的总分是 36 分

sql
--简单题窗口写法
select 
gender,day,sum(score_points) over(partition by gender order by day) as total
from 
(
select
gender,to_char(day,'yyyy-mm-dd') as day ,sum(score_points) score_points
from 
Scores
group by  gender,day
) t1
sql
SELECT
    S1.gender,
    S1.day,
    SUM(S2.score_points) total
FROM
    Scores S1
LEFT JOIN
    Scores S2
ON S1.gender = S2.gender AND S1.day >= S2.day
GROUP BY
    S1.gender,
    S1.day
ORDER BY
    S1.gender,
    S1.day

89.餐厅营业额变化增长(窗口函数)

写一条 SQL 查询计算以 7 天(某日期 + 该日期前的 6 天)为一个时间段的顾客消费平均值

表: Customer

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
| visited_on    | date    |
| amount        | int     |
+---------------+---------+

(customer_id, visited_on) 是该表的主键
该表包含一家餐馆的顾客交易数据
visited_on 表示 (customer_id) 的顾客在 visited_on 那天访问了餐馆
amount 是一个顾客某一天的消费总额
 

你是餐馆的老板,现在你想分析一下可能的营业额变化增长(每天至少有一位顾客)

写一条 SQL 查询计算以 7 天(某日期 + 该日期前的 6 天)为一个时间段的顾客消费平均值

查询结果格式的例子如下:

查询结果按 visited_on 排序
average_amount 要 保留两位小数,日期数据的格式为 ('YYYY-MM-DD')
 

Customer 表:

text
+-------------+--------------+--------------+-------------+
| customer_id | name         | visited_on   | amount      |
+-------------+--------------+--------------+-------------+
| 1           | Jhon         | 2019-01-01   | 100         |
| 2           | Daniel       | 2019-01-02   | 110         |
| 3           | Jade         | 2019-01-03   | 120         |
| 4           | Khaled       | 2019-01-04   | 130         |
| 5           | Winston      | 2019-01-05   | 110         | 
| 6           | Elvis        | 2019-01-06   | 140         | 
| 7           | Anna         | 2019-01-07   | 150         |
| 8           | Maria        | 2019-01-08   | 80          |
| 9           | Jaze         | 2019-01-09   | 110         | 
| 1           | Jhon         | 2019-01-10   | 130         | 
| 3           | Jade         | 2019-01-10   | 150         | 
+-------------+--------------+--------------+-------------+

结果表:

text
+--------------+--------------+----------------+
| visited_on   | amount       | average_amount |
+--------------+--------------+----------------+
| 2019-01-07   | 860          | 122.86         |
| 2019-01-08   | 840          | 120            |
| 2019-01-09   | 840          | 120            |
| 2019-01-10   | 1000         | 142.86         |
+--------------+--------------+----------------+

第一个七天消费平均值从 2019-01-01 到 2019-01-07 是 (100 + 110 + 120 + 130 + 110 + 140 + 150)/7 = 122.86
第二个七天消费平均值从 2019-01-02 到 2019-01-08 是 (110 + 120 + 130 + 110 + 140 + 150 + 80)/7 = 120
第三个七天消费平均值从 2019-01-03 到 2019-01-09 是 (120 + 130 + 110 + 140 + 150 + 80 + 110)/7 = 120
第四个七天消费平均值从 2019-01-04 到 2019-01-10 是 (130 + 110 + 140 + 150 + 80 + 110 + 130 + 150)/7 = 142.8

sql
--简单题,窗口写法我写的比较麻烦,直接过滤就行了
--例如 having datediff(max(b.visited_on),min(b.visited_on)) = 6
select
t1.visited_on,round(s1,2) as amount,round(s2,2) as average_amount
from 
(
select
distinct to_char(visited_on ,'yyyy-mm-dd') visited_on
from 
Customer
where to_char(visited_on - 6,'yyyy-mm-dd') 
in (select to_char(visited_on ,'yyyy-mm-dd') from  Customer ) ) t1
join 
(
select
to_char(visited_on ,'yyyy-mm-dd') visited,
sum(sum(amount)) over(order by visited_on rows between 6 preceding and current row) s1 ,
avg(sum(amount)) over(order by visited_on rows between 6 preceding and current row) s2
from 
Customer
group by visited_on ) t2
on t1.visited_on = t2.visited
sql
--用序列函数来过滤.....超时了....
select
visited_on,round(s1,2) as amount,round(s2,2) as average_amount
from 
(
select
to_char(visited_on ,'yyyy-mm-dd') visited_on,
sum(sum(amount)) over(order by visited_on rows between 6 preceding and current row) s1 ,
avg(sum(amount)) over(order by visited_on rows between 6 preceding and current row) s2 ,
rank() over(order by visited_on) s3
from 
Customer
group by visited_on ) t2
where s3>=7
sql
--评论区的自连接写法
SELECT
	a.visited_on,
	sum( b.amount ) AS amount,
	round(sum( b.amount ) / 7, 2 ) AS average_amount 
FROM
	(SELECT DISTINCT visited_on FROM customer) a 
JOIN 
	customer b 
ON 
	datediff( a.visited_on, b.visited_on ) BETWEEN 0 AND 6 
WHERE
	a.visited_on >= (SELECT min(visited_on) FROM customer) + 6 
GROUP BY
	a.visited_on

主要学习要点就是怎么过滤出有前七天时间的日期(效率)
学习一下窗口大小 还有datediff()与between and 的连用

90.广告效果

写一条SQL语句来查询每一条广告的 ctr

表: Ads

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ad_id         | int     |
| user_id       | int     |
| action        | enum    |
+---------------+---------+

(ad_id, user_id) 是该表的主键
该表的每一行包含一条广告的 ID(ad_id),用户的 ID(user_id) 和用户对广告采取的行为 (action)
action 列是一个枚举类型 ('Clicked', 'Viewed', 'Ignored') 。
 

一家公司正在运营这些广告并想计算每条广告的效果。

广告效果用点击通过率(Click-Through Rate:CTR)来衡量,公式如下:

写一条SQL语句来查询每一条广告的 ctr ,

 ctr 要保留两位小数。结果需要按 ctr 降序、按 ad_id 升序 进行排序。

 

查询结果示例如下:

Ads 表:

text
+-------+---------+---------+
| ad_id | user_id | action  |
+-------+---------+---------+
| 1     | 1       | Clicked |
| 2     | 2       | Clicked |
| 3     | 3       | Viewed  |
| 5     | 5       | Ignored |
| 1     | 7       | Ignored |
| 2     | 7       | Viewed  |
| 3     | 5       | Clicked |
| 1     | 4       | Viewed  |
| 2     | 11      | Viewed  |
| 1     | 2       | Clicked |
+-------+---------+---------+

结果表:

text
+-------+-------+
| ad_id | ctr   |
+-------+-------+
| 1     | 66.67 |
| 3     | 50.00 |
| 2     | 33.33 |
| 5     | 0.00  |
+-------+-------+

对于 ad_id = 1, ctr = (2/(2+1)) * 100 = 66.67
对于 ad_id = 2, ctr = (1/(1+2)) * 100 = 33.33
对于 ad_id = 3, ctr = (1/(1+1)) * 100 = 50.00
对于 ad_id = 5, ctr = 0.00, 注意 ad_id = 5 没有被点击 (Clicked) 或查看 (Viewed) 过
注意我们不关心 action 为 Ingnored 的广告
结果按 ctr(降序),ad_id(升序)排序

sql
--简单题注意考察对null的处理
select
ad_id,ifnull(round(sum(action="Clicked") /(sum(action <> "Ignored")) *100,2),0.00) ctr
from 
Ads
group by ad_id
order by ctr desc ,ad_id 

练习题 9

91.列出指定时间段所有下单的产品

写一个 SQL 语句,要求获取在 2020 年 2 月份下单的数量不少于 100 的产品的名字和数目

表: Products

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| product_id       | int     |
| product_name     | varchar |
| product_category | varchar |
+------------------+---------+

product_id 是该表主键。
该表包含该公司产品的数据。
表: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| order_date    | date    |
| unit          | int     |
+---------------+---------+

该表无主键,可能包含重复行。
product_id 是表单 Products 的外键。
unit 是在日期 order_date 内下单产品的数目。
 

写一个 SQL 语句,要求获取在 2020 年 2 月份下单的数量不少于 100 的产品的名字和数目。

返回结果表单的顺序无要求。

 

查询结果的格式如下:

Products 表:

text
+-------------+-----------------------+------------------+
| product_id  | product_name          | product_category |
+-------------+-----------------------+------------------+
| 1           | Leetcode Solutions    | Book             |
| 2           | Jewels of Stringology | Book             |
| 3           | HP                    | Laptop           |
| 4           | Lenovo                | Laptop           |
| 5           | Leetcode Kit          | T-shirt          |
+-------------+-----------------------+------------------+

Orders 表:

text
+--------------+--------------+----------+
| product_id   | order_date   | unit     |
+--------------+--------------+----------+
| 1            | 2020-02-05   | 60       |
| 1            | 2020-02-10   | 70       |
| 2            | 2020-01-18   | 30       |
| 2            | 2020-02-11   | 80       |
| 3            | 2020-02-17   | 2        |
| 3            | 2020-02-24   | 3        |
| 4            | 2020-03-01   | 20       |
| 4            | 2020-03-04   | 30       |
| 4            | 2020-03-04   | 60       |
| 5            | 2020-02-25   | 50       |
| 5            | 2020-02-27   | 50       |
| 5            | 2020-03-01   | 50       |
+--------------+--------------+----------+

Result 表:

text
+--------------------+---------+
| product_name       | unit    |
+--------------------+---------+
| Leetcode Solutions | 130     |
| Leetcode Kit       | 100     |
+--------------------+---------+

2020 年 2 月份下单 product_id = 1 的产品的数目总和为 (60 + 70) = 130
2020 年 2 月份下单 product_id = 2 的产品的数目总和为 80
2020 年 2 月份下单 product_id = 3 的产品的数目总和为 (2 + 3) = 5
2020 年 2 月份 product_id = 4 的产品并没有下单
2020 年 2 月份下单 product_id = 5 的产品的数目总和为 (50 + 50) = 100

sql
-- 简单题,使用like来获取年份效率高
select
product_name,sum(unit) as unit
from
Products t1
join Orders t2
on t1.product_id = t2.product_id and left(order_date,7) = "2020-02"
group by product_name
having sum(unit) >= 100

总结一下获取年份的方法

text
(1) order_date between '2020-02-01' and '2020-02-29'  
(2) order_date like '2020-02%'  
(3) DATE_FORMAT(order_date, "%Y-%m") = "2020-02"   
(4) LEFT(order_date, 7) 或 substr(1, 7)

92.每次访问的交易次数(构造0-max)☆

银行想要得到银行客户在一次访问时的交易次数和相应的在一次访问时该交易次数的客户数量的图表
写一条 SQL 查询多少客户访问了银行但没有进行任何交易,多少客户访问了银行进行了一次交易等等

表: Visits

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| visit_date    | date    |
+---------------+---------+

(user_id, visit_date) 是该表的主键
该表的每行表示 user_id 在 visit_date 访问了银行
 

表: Transactions

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| user_id          | int     |
| transaction_date | date    |
| amount           | int     |
+------------------+---------+

该表没有主键,所以可能有重复行
该表的每一行表示 user_id 在 transaction_date 完成了一笔 amount 数额的交易
可以保证用户 (user) 在 transaction_date 访问了银行 (也就是说 Visits 表包含 (user_id, transaction_date) 行)
 

银行想要得到银行客户在一次访问时的交易次数和相应的在一次访问时该交易次数的客户数量的图表

写一条 SQL 查询多少客户访问了银行但没有进行任何交易,多少客户访问了银行进行了一次交易等等

结果包含两列:

transactions_count: 客户在一次访问中的交易次数
visits_count: 在 transactions_count 交易次数下相应的一次访问时的客户数量
transactions_count 的值从 0 到所有用户一次访问中的 max(transactions_count) 

按 transactions_count 排序

下面是查询结果格式的例子:

Visits 表:

text
+---------+------------+
| user_id | visit_date |
+---------+------------+
| 1       | 2020-01-01 |
| 2       | 2020-01-02 |
| 12      | 2020-01-01 |
| 19      | 2020-01-03 |
| 1       | 2020-01-02 |
| 2       | 2020-01-03 |
| 1       | 2020-01-04 |
| 7       | 2020-01-11 |
| 9       | 2020-01-25 |
| 8       | 2020-01-28 |
+---------+------------+

Transactions 表:

text
+---------+------------------+--------+
| user_id | transaction_date | amount |
+---------+------------------+--------+
| 1       | 2020-01-02       | 120    |
| 2       | 2020-01-03       | 22     |
| 7       | 2020-01-11       | 232    |
| 1       | 2020-01-04       | 7      |
| 9       | 2020-01-25       | 33     |
| 9       | 2020-01-25       | 66     |
| 8       | 2020-01-28       | 1      |
| 9       | 2020-01-25       | 99     |
+---------+------------------+--------+

结果表:

text
+--------------------+--------------+
| transactions_count | visits_count |
+--------------------+--------------+
| 0                  | 4            |
| 1                  | 5            |
| 2                  | 0            |
| 3                  | 1            |
+--------------------+--------------+
  • 对于 transactions_count = 0, visits 中 (1, "2020-01-01"), (2, "2020-01-02"), (12, "2020-01-01") 和 (19, "2020-01-03") 没有进行交易,所以 visits_count = 4 。
  • 对于 transactions_count = 1, visits 中 (2, "2020-01-03"), (7, "2020-01-11"), (8, "2020-01-28"), (1, "2020-01-02") 和 (1, "2020-01-04") 进行了一次交易,所以 visits_count = 5 。
  • 对于 transactions_count = 2, 没有客户访问银行进行了两次交易,所以 visits_count = 0 。
  • 对于 transactions_count = 3, visits 中 (9, "2020-01-25") 进行了三次交易,所以 visits_count = 1 。
  • 对于 transactions_count >= 4, 没有客户访问银行进行了超过3次交易,所以我们停止在 transactions_count = 3 。

这个例子的图表

sql
-- 难题没想到使用序列函数和0 union all 构造0-max
with temp1 as (
    select transactions_count,count(user_id) visits_count
    from (
        select v.user_id,count(t.user_id) transactions_count
        from Visits v
        left join Transactions t
        on v.user_id = t.user_id and v.visit_date = transaction_date
        group by v.user_id,v.visit_date
    ) a
    group by transactions_count
)

select temp2.transactions_count,ifnull(temp1.visits_count,0) visits_count
from (
    select 0 transactions_count
    union
    select row_number() over (order by transaction_date) transactions_count
    from Transactions
) temp2
left join temp1
on temp2.transactions_count = temp1.transactions_count
where temp2.transactions_count <= (
    select max(transactions_count)
    from temp1
)

93.电影评分

请你编写一组 SQL 查询:
查找评论电影数量最多的用户名。
如果出现平局,返回字典序较小的用户名。
查找在 2020 年 2 月 平均评分最高 的电影名称。
如果出现平局,返回字典序较小的电影名称。

表:Movies

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| movie_id      | int     |
| title         | varchar |
+---------------+---------+

movie_id 是这个表的主键。
title 是电影的名字。
表:Users

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| name          | varchar |
+---------------+---------+

user_id 是表的主键。
表:Movie_Rating

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| movie_id      | int     |
| user_id       | int     |
| rating        | int     |
| created_at    | date    |
+---------------+---------+

(movie_id, user_id) 是这个表的主键。
这个表包含用户在其评论中对电影的评分 rating 。
created_at 是用户的点评日期。
 

请你编写一组 SQL 查询:

查找评论电影数量最多的用户名。
如果出现平局,返回字典序较小的用户名。

查找在 2020 年 2 月 平均评分最高 的电影名称。
如果出现平局,返回字典序较小的电影名称。

查询分两行返回,查询结果格式如下例所示:

Movies 表:

text
+-------------+--------------+
| movie_id    |  title       |
+-------------+--------------+
| 1           | Avengers     |
| 2           | Frozen 2     |
| 3           | Joker        |
+-------------+--------------+

Users 表:

text
+-------------+--------------+
| user_id     |  name        |
+-------------+--------------+
| 1           | Daniel       |
| 2           | Monica       |
| 3           | Maria        |
| 4           | James        |
+-------------+--------------+

Movie_Rating 表:

text
+-------------+--------------+--------------+-------------+
| movie_id    | user_id      | rating       | created_at  |
+-------------+--------------+--------------+-------------+
| 1           | 1            | 3            | 2020-01-12  |
| 1           | 2            | 4            | 2020-02-11  |
| 1           | 3            | 2            | 2020-02-12  |
| 1           | 4            | 1            | 2020-01-01  |
| 2           | 1            | 5            | 2020-02-17  | 
| 2           | 2            | 2            | 2020-02-01  | 
| 2           | 3            | 2            | 2020-03-01  |
| 3           | 1            | 3            | 2020-02-22  | 
| 3           | 2            | 4            | 2020-02-25  | 
+-------------+--------------+--------------+-------------+

Result 表:

text
+--------------+
| results      |
+--------------+
| Daniel       |
| Frozen 2     |
+--------------+

Daniel 和 Monica 都点评了 3 部电影("Avengers", "Frozen 2" 和 "Joker") 但是 Daniel 字典序比较小。
Frozen 2 和 Joker 在 2 月的评分都是 3.5,但是 Frozen 2 的字典序比较小。

sql
--简单题,为什么union all 上下要打括号?
(
select
name results 
from
Users t1
join Movie_Rating t2
on t1.user_id = t2.user_id
group by name
order by count(distinct movie_id) desc,name
limit 1 ) 
union all
(
select 
title 
from 
Movies t3
join Movie_Rating t4
on t3.movie_id = t4.movie_id  
where left(created_at ,7) = "2020-02"
group by title 
order by avg(rating ) desc, title 
limit 1 ) 

94院系无效的学生

写一条 SQL 语句以查询那些所在院系不存在的学生的 id 和姓名

院系表: Departments

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+

id 是该表的主键
该表包含一所大学每个院系的 id 信息
 

学生表: Students

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
| department_id | int     |
+---------------+---------+

id 是该表的主键
该表包含一所大学每个学生的 id 和他/她就读的院系信息
 

写一条 SQL 语句以查询那些所在院系不存在的学生的 id 和姓名

可以以任何顺序返回结果

下面是返回结果格式的例子

Departments 表:

text
+------+--------------------------+
| id   | name                     |
+------+--------------------------+
| 1    | Electrical Engineering   |
| 7    | Computer Engineering     |
| 13   | Bussiness Administration |
+------+--------------------------+

Students 表:

text
+------+----------+---------------+
| id   | name     | department_id |
+------+----------+---------------+
| 23   | Alice    | 1             |
| 1    | Bob      | 7             |
| 5    | Jennifer | 13            |
| 2    | John     | 14            |
| 4    | Jasmine  | 77            |
| 3    | Steve    | 74            |
| 6    | Luis     | 1             |
| 8    | Jonathan | 7             |
| 7    | Daiana   | 33            |
| 11   | Madelynn | 1             |
+------+----------+---------------+

结果表:

text
+------+----------+
| id   | name     |
+------+----------+
| 2    | John     |
| 7    | Daiana   |
| 4    | Jasmine  |
| 3    | Steve    |
+------+----------+

John, Daiana, Steve 和 Jasmine 所在的院系分别是 14, 33, 74 和 77, 其中 14, 33, 74 和 77 并不存在于院系表

sql
--简单题
select
s.id,s.name
from 
Students s left join Departments d on s.department_id = d.id 
where d.id is null
sql
select id, name
from Students
where department_id not in (select id from Departments)

join之间的差别
https://leetcode-cn.com/problems/nth-highest-salary/solution/mysql-zi-ding-yi-bian-liang-by-luanz/

95.活动参与者

写一条 SQL 查询那些既没有最多,也没有最少参与者的活动的名字

表: Friends

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
| activity      | varchar |
+---------------+---------+

id 是朋友的 id 和该表的主键
name 是朋友的名字
activity 是朋友参加的活动的名字
表: Activities

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+

id 是该表的主键
name 是活动的名字
 

写一条 SQL 查询那些既没有最多,也没有最少参与者的活动的名字

可以以任何顺序返回结果,Activities 表的每项活动的参与者都来自 Friends 表

注意:名称相同 id 不同的参与者算作两个人

下面是查询结果格式的例子:

Friends 表:

text
+------+--------------+---------------+
| id   | name         | activity      |
+------+--------------+---------------+
| 1    | Jonathan D.  | Eating        |
| 2    | Jade W.      | Singing       |
| 3    | Victor J.    | Singing       |
| 4    | Elvis Q.     | Eating        |
| 5    | Daniel A.    | Eating        |
| 6    | Bob B.       | Horse Riding  |
+------+--------------+---------------+

Activities 表:

text
+------+--------------+
| id   | name         |
+------+--------------+
| 1    | Eating       |
| 2    | Singing      |
| 3    | Horse Riding |
+------+--------------+

Result 表:

text
+--------------+
| activity     |
+--------------+
| Singing      |
+--------------+

Eating 活动有三个人参加, 是最多人参加的活动 (Jonathan D. , Elvis Q. and Daniel A.)
Horse Riding 活动有一个人参加, 是最少人参加的活动 (Bob B.)
Singing 活动有两个人参加 (Victor J. and Jade W.)

sql
-- 简单题,窗口
select
name as activity 
from 
Activities
where name not in 
(
select
activity 
from 
(
select
activity,
dense_rank() over(order by count(1) desc) as max_count,
dense_rank() over(order by count(1) asc) as min_count
from
Friends f 
group by 
activity
) t1
where max_count =1 or min_count = 1
)
sql
with a as 
(select activity, count(*) amount
from friends
group by activity)

select activity
from friends
group by activity
having count(*) > (select min(amount) from a) 
and count(*) < (select max(amount) from a)

96.顾客的可信联系人数量

为每张发票 invoice_id 编写一个SQL查询以查找以下内容:
customer_name:与发票相关的顾客名称。
price:发票的价格。
contacts_cnt:该顾客的联系人数量。
trusted_contacts_cnt:可信联系人的数量:既是该顾客的联系人又是商店顾客的联系人数量(即:可信联系人的电子邮件存在于客户表中)。

顾客表:Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
| email         | varchar |
+---------------+---------+

customer_id 是这张表的主键。
此表的每一行包含了某在线商店顾客的姓名和电子邮件。
 

联系方式表:Contacts

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | id      |
| contact_name  | varchar |
| contact_email | varchar |
+---------------+---------+

(user_id, contact_email) 是这张表的主键。
此表的每一行表示编号为 user_id 的顾客的某位联系人的姓名和电子邮件。
此表包含每位顾客的联系人信息,但顾客的联系人不一定存在于顾客表中。
 

发票表:Invoices

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| invoice_id   | int     |
| price        | int     |
| user_id      | int     |
+--------------+---------+

invoice_id 是这张表的主键。
此表的每一行分别表示编号为 user_id 的顾客拥有有一张编号为 invoice_id、价格为 price 的发票。
 

为每张发票 invoice_id 编写一个SQL查询以查找以下内容:

customer_name:与发票相关的顾客名称。
price:发票的价格。
contacts_cnt:该顾客的联系人数量。
trusted_contacts_cnt:可信联系人的数量:既是该顾客的联系人又是商店顾客的联系人数量(即:可信联系人的电子邮件存在于客户表中)。
将查询的结果按照 invoice_id 排序。

查询结果的格式如下例所示:

Customers table:

text
+-------------+---------------+--------------------+
| customer_id | customer_name | email              |
+-------------+---------------+--------------------+
| 1           | Alice         | alice@leetcode.com |
| 2           | Bob           | bob@leetcode.com   |
| 13          | John          | john@leetcode.com  |
| 6           | Alex          | alex@leetcode.com  |
+-------------+---------------+--------------------+

Contacts table:

text
+-------------+--------------+--------------------+
| user_id     | contact_name | contact_email      |
+-------------+--------------+--------------------+
| 1           | Bob          | bob@leetcode.com   |
| 1           | John         | john@leetcode.com  |
| 1           | Jal          | jal@leetcode.com   |
| 2           | Omar         | omar@leetcode.com  |
| 2           | Meir         | meir@leetcode.com  |
| 6           | Alice        | alice@leetcode.com |
+-------------+--------------+--------------------+

Invoices table:

text
+------------+-------+---------+
| invoice_id | price | user_id |
+------------+-------+---------+
| 77         | 100   | 1       |
| 88         | 200   | 1       |
| 99         | 300   | 2       |
| 66         | 400   | 2       |
| 55         | 500   | 13      |
| 44         | 60    | 6       |
+------------+-------+---------+

Result table:

text
+------------+---------------+-------+--------------+----------------------+
| invoice_id | customer_name | price | contacts_cnt | trusted_contacts_cnt |
+------------+---------------+-------+--------------+----------------------+
| 44         | Alex          | 60    | 1            | 1                    |
| 55         | John          | 500   | 0            | 0                    |
| 66         | Bob           | 400   | 2            | 0                    |
| 77         | Alice         | 100   | 3            | 2                    |
| 88         | Alice         | 200   | 3            | 2                    |
| 99         | Bob           | 300   | 2            | 0                    |
+------------+---------------+-------+--------------+----------------------+

Alice 有三位联系人,其中两位(Bob 和 John)是可信联系人
Bob 有两位联系人, 他们中的任何一位都不是可信联系人
Alex 只有一位联系人(Alice),并是一位可信联系人
John 没有任何联系人

sql
--简单题,对if子查询查询优化一下,采用自连接
select
invoice_id,customer_name,price,contacts_cnt,trusted_contacts_cnt 
from 
(
select
invoice_id,customer_name,price,customer_id
from
Invoices
join Customers on Invoices.user_id = Customers.customer_id
) s1
join 
(
select
customer_id,ifnull(count(contact_name),0) contacts_cnt ,
ifnull(sum(if(contact_name in (select customer_name from Customers) ,1,0)),0) trusted_contacts_cnt
from
Customers c1 
left join Contacts c2 on c1.customer_id = c2.user_id
group by customer_id
) s2
on s1.customer_id =s2.customer_id
order by invoice_id
sql
select
    i.invoice_id,
    cut.customer_name customer_name,
    i.price,
    count(co.contact_email) contacts_cnt,
    count(cu.email) trusted_contacts_cnt
from Invoices i
left join Customers cut on i.user_id = cut.customer_id
left join Contacts co on i.user_id = co.user_id
left join Customers cu on co.contact_email = cu.email
group by i.invoice_id,i.user_id
order by i.invoice_id

97.获取最近第二次的活动(组内count)

写一条SQL查询展示每一位用户 最近第二次 的活动

表: UserActivity

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| username      | varchar |
| activity      | varchar |
| startDate     | Date    |
| endDate       | Date    |
+---------------+---------+

该表不包含主键
该表包含每个用户在一段时间内进行的活动的信息
名为 username 的用户在 startDate 到 endDate 日内有一次活动
 

写一条SQL查询展示每一位用户 最近第二次 的活动

如果用户仅有一次活动,返回该活动

一个用户不能同时进行超过一项活动,以 任意 顺序返回结果

下面是查询结果格式的例子:

UserActivity 表:

text
+------------+--------------+-------------+-------------+
| username   | activity     | startDate   | endDate     |
+------------+--------------+-------------+-------------+
| Alice      | Travel       | 2020-02-12  | 2020-02-20  |
| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
| Alice      | Travel       | 2020-02-24  | 2020-02-28  |
| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+

Result 表:

text
+------------+--------------+-------------+-------------+
| username   | activity     | startDate   | endDate     |
+------------+--------------+-------------+-------------+
| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+

Alice 最近一次的活动是从 2020-02-24 到 2020-02-28 的旅行, 在此之前的 2020-02-21 到 2020-02-23 她进行了舞蹈
Bob 只有一条记录,我们就取这条记录

sql
-- 简单题,优化一下
select
username, activity,to_char(startDate,'yyyy-mm-dd') startDate,to_char(endDate,'yyyy-mm-dd') endDate 
from 
(
select
username,activity,startDate,endDate,
row_number() over(partition by username order by startDate  ) as rn1  
from 
(
select
username,activity,startDate,endDate,
row_number() over(partition by username order by startDate desc ) as rn 
from
UserActivity ) t1 
where rn = 1 or rn = 2  ) t2
where rn1 = 1
sql
--没想到,采用一个组内全局的count来获取
select username,activity,startDate,endDate
from(
    select *,
        row_number() over (partition by username order by startDate desc) r,
        count(*) over (partition by username) c
    from UserActivity
) a
where c = 1 or r = 2

98.使用唯一标识码替换员工id

写一段SQL查询来展示每位用户的 唯一标识码(unique ID );如果某位员工没有唯一标识码,使用 null 填充即可。

Employees 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+

id 是这张表的主键。
这张表的每一行分别代表了某公司其中一位员工的名字和 ID 。
 

EmployeeUNI 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| unique_id     | int     |
+---------------+---------+

(id, unique_id) 是这张表的主键。
这张表的每一行包含了该公司某位员工的 ID 和他的唯一标识码(unique ID)。
 

写一段SQL查询来展示每位用户的 唯一标识码(unique ID );如果某位员工没有唯一标识码,使用 null 填充即可。

你可以以 任意 顺序返回结果表。

查询结果的格式如下例所示:

Employees table:

text
+----+----------+
| id | name     |
+----+----------+
| 1  | Alice    |
| 7  | Bob      |
| 11 | Meir     |
| 90 | Winston  |
| 3  | Jonathan |
+----+----------+

EmployeeUNI table:

text
+----+-----------+
| id | unique_id |
+----+-----------+
| 3  | 1         |
| 11 | 2         |
| 90 | 3         |
+----+-----------+

EmployeeUNI table:

text
+-----------+----------+
| unique_id | name     |
+-----------+----------+
| null      | Alice    |
| null      | Bob      |
| 2         | Meir     |
| 3         | Winston  |
| 1         | Jonathan |
+-----------+----------+

Alice and Bob 没有唯一标识码, 因此我们使用 null 替代。
Meir 的唯一标识码是 2 。
Winston 的唯一标识码是 3 。
Jonathan 唯一标识码是 1

sql
--简单题
select
 unique_id,name
from
Employees
left join EmployeeUNI on EmployeeUNI.id = Employees.id

99.按年度列出销售总额

编写一段 SQL 查询每个产品每年的总销售额,并包含 product_id, product_name 以及 report_year 等信息。
销售年份的日期介于 2018 年到 2020 年之间。你返回的结果需要按 product_id 和 report_year 排序。

Product 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
+---------------+---------+

product_id 是这张表的主键。
product_name 是产品的名称。
 

Sales 表:

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| product_id          | int     |
| period_start        | date    |
| period_end          | date    |
| average_daily_sales | int     |
+---------------------+---------+

product_id 是这张表的主键。
period_start 和 period_end 是该产品销售期的起始日期和结束日期,且这两个日期包含在销售期内。
average_daily_sales 列存储销售期内该产品的日平均销售额。
 

编写一段 SQL 查询每个产品每年的总销售额,并包含 product_id, product_name 以及 report_year 等信息。

销售年份的日期介于 2018 年到 2020 年之间。你返回的结果需要按 product_id 和 report_year 排序。

查询结果格式如下例所示:

Product table:

text
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 1          | LC Phone     |
| 2          | LC T-Shirt   |
| 3          | LC Keychain  |
+------------+--------------+

Sales table:

text
+------------+--------------+-------------+---------------------+
| product_id | period_start | period_end  | average_daily_sales |
+------------+--------------+-------------+---------------------+
| 1          | 2019-01-25   | 2019-02-28  | 100                 |
| 2          | 2018-12-01   | 2020-01-01  | 10                  |
| 3          | 2019-12-01   | 2020-01-31  | 1                   |
+------------+--------------+-------------+---------------------+

Result table:

text
+------------+--------------+-------------+--------------+
| product_id | product_name | report_year | total_amount |
+------------+--------------+-------------+--------------+
| 1          | LC Phone     |    2019     | 3500         |
| 2          | LC T-Shirt   |    2018     | 310          |
| 2          | LC T-Shirt   |    2019     | 3650         |
| 2          | LC T-Shirt   |    2020     | 10           |
| 3          | LC Keychain  |    2019     | 31           |
| 3          | LC Keychain  |    2020     | 31           |
+------------+--------------+-------------+--------------+

LC Phone 在 2019-01-25 至 2019-02-28 期间销售,该产品销售时间总计35天。销售总额 35100 = 3500。
LC T-shirt 在 2018-12-01 至 2020-01-01 期间销售,该产品在2018年、2019年、2020年的销售时间分别是31天、365天、1天,2018年、2019年、2020年的销售总额分别是31
10=310、36510=3650、110=10。
LC Keychain 在 2019-12-01 至 2020-01-31 期间销售,该产品在2019年、2020年的销售时间分别是:31天、31天,2019年、2020年的销售总额分别是311=31、311=31。

sql
--简单题,怎么优化一下吧负数给在里面那层就过滤掉
select 
x1.product_id,product_name,report_year,total_amount
from 
(
select
product_id,
"2020" as report_year ,
(datediff(period_end,"2020-01-01") + 1 ) * average_daily_sales as total_amount
from
Sales
where  period_end >= "2020-01-01" 
union all 
(
select 
product_id,
"2019" as report_year,
(datediff(
if(datediff(period_end,"2019-12-31")>=0,"2019-12-31",period_end),
if(datediff(period_start,"2019-01-01")<=0,"2019-01-01",period_start)
)  +1 ) * average_daily_sales 
from
Sales )
union all 
(
select 
product_id,
"2018" as report_year,
(datediff(
if(datediff(period_end,"2018-12-31")>=0,"2018-12-31",period_end),
if(datediff(period_start,"2018-01-01")<=0,"2018-01-01",period_start)
)  +1 ) * average_daily_sales 
from
Sales ) ) x1 
join Product on x1.product_id = Product.product_id
where total_amount>=0
order by product_id,report_year 
sql
SELECT
    CAST(p.product_id AS CHAR) product_id,
    p.product_name,
    report_year,
    (DATEDIFF(IF(end_dt>period_end,period_end,end_dt),IF(start_dt>period_start,start_dt,period_start)) + 1) * average_daily_sales total_amount
FROM
    Product p
CROSS JOIN
    (
    SELECT '2018' report_year,'2018-01-01' start_dt,'2018-12-31' end_dt
    UNION ALL
    SELECT '2019' report_year,'2019-01-01' start_dt,'2019-12-31' end_dt
    UNION ALL
    SELECT '2020' report_year,'2020-01-01' start_dt,'2020-12-31' end_dt
    ) y
INNER JOIN
    Sales s
ON p.product_id = s.product_id
WHERE
    period_start<=end_dt AND period_end>=start_dt
ORDER BY
    product_id,
    report_year
sql
WITH report_year_list AS (
    SELECT 2018 AS report_year
    UNION
    SELECT 2019 AS report_year
    UNION 
    SELECT 2020 AS report_year
),

product_report_year AS (
    SELECT s.product_id, s.period_start, s.period_end, s.average_daily_sales, r.report_year
    FROM Sales s JOIN report_year_list r
    ON YEAR(s.period_start) <= r.report_year AND r.report_year <= YEAR(s.period_end)    
)

SELECT
    CAST(p.product_id AS CHAR) AS product_id,
    p.product_name,
    CAST(pr.report_year AS CHAR) AS report_year,
    CASE
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2018 THEN (1+DATEDIFF(period_end, period_start))*average_daily_sales
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2019 AND report_year = 2018 THEN (1+DATEDIFF("2018-12-31", period_start))*average_daily_sales
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2019 AND report_year = 2019 THEN (1+DATEDIFF(period_end, "2019-01-01"))*average_daily_sales
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2020 AND report_year = 2018 THEN (1+DATEDIFF("2018-12-31", period_start))*average_daily_sales
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2020 AND report_year = 2019 THEN (1+DATEDIFF("2019-12-31", "2019-01-01"))*average_daily_sales
        WHEN YEAR(period_start) = 2018 AND YEAR(period_end) = 2020 AND report_year = 2020 THEN (1+DATEDIFF(period_end, "2020-01-01"))*average_daily_sales
        WHEN YEAR(period_start) = 2019 AND YEAR(period_end) = 2019 THEN (1+DATEDIFF(period_end, period_start))*average_daily_sales
        WHEN YEAR(period_start) = 2019 AND YEAR(period_end) = 2020 AND report_year = 2019 THEN (1+DATEDIFF("2019-12-31", period_start))*average_daily_sales
        WHEN YEAR(period_start) = 2019 AND YEAR(period_end) = 2020 AND report_year = 2020 THEN (1+DATEDIFF(period_end, "2020-01-01"))*average_daily_sales
        WHEN YEAR(period_start) = 2020 AND YEAR(period_end) = 2020 THEN (1+DATEDIFF(period_end, period_start))*average_daily_sales
    END AS total_amount
FROM product_report_year pr INNER JOIN Product p
ON pr.product_id = p.product_id
ORDER BY CAST(p.product_id AS CHAR), CAST(pr.report_year AS CHAR)

100.股票的资本损益

编写一个SQL查询来报告每支股票的资本损益

Stocks 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| stock_name    | varchar |
| operation     | enum    |
| operation_day | int     |
| price         | int     |
+---------------+---------+

(stock_name, day) 是这张表的主键
operation 列使用的是一种枚举类型,包括:('Sell','Buy')
此表的每一行代表了名为 stock_name 的某支股票在 operation_day 这一天的操作价格。
保证股票的每次'Sell'操作前,都有相应的'Buy'操作。
 

编写一个SQL查询来报告每支股票的资本损益。

股票的资本损益是一次或多次买卖股票后的全部收益或损失。

以任意顺序返回结果即可。

SQL查询结果的格式如下例所示:

Stocks 表:

text
+---------------+-----------+---------------+--------+
| stock_name    | operation | operation_day | price  |
+---------------+-----------+---------------+--------+
| Leetcode      | Buy       | 1             | 1000   |
| Corona Masks  | Buy       | 2             | 10     |
| Leetcode      | Sell      | 5             | 9000   |
| Handbags      | Buy       | 17            | 30000  |
| Corona Masks  | Sell      | 3             | 1010   |
| Corona Masks  | Buy       | 4             | 1000   |
| Corona Masks  | Sell      | 5             | 500    |
| Corona Masks  | Buy       | 6             | 1000   |
| Handbags      | Sell      | 29            | 7000   |
| Corona Masks  | Sell      | 10            | 10000  |
+---------------+-----------+---------------+--------+

Result 表:

text
+---------------+-------------------+
| stock_name    | capital_gain_loss |
+---------------+-------------------+
| Corona Masks  | 9500              |
| Leetcode      | 8000              |
| Handbags      | -23000            |
+---------------+-------------------+

Leetcode 股票在第一天以1000美元的价格买入,在第五天以9000美元的价格卖出。资本收益=9000-1000=8000美元。
Handbags 股票在第17天以30000美元的价格买入,在第29天以7000美元的价格卖出。资本损失=7000-30000=-23000美元。
Corona Masks 股票在第1天以10美元的价格买入,在第3天以1010美元的价格卖出。在第4天以1000美元的价格再次购买,在第5天以500美元的价格出售。最后,它在第6天以1000美元的价格被买走,在第10天以10000美元的价格被卖掉。资本损益是每次(’Buy'->'Sell')操作资本收益或损失的和=(1010-10)+(500-1000)+(10000-1000)=1000-500+9000=9500美元。

sql
--简单题
select
stock_name,
sum(if(operation = "Buy",-price,price)) capital_gain_loss
from
Stocks
group by  stock_name

练习题 10

101.购买了产品A产品B却没有购买产品C的顾客

请你设计 SQL 查询来报告购买了产品 A 和产品 B 却没有购买产品 C 的顾客的 ID 和姓名( customer_id 和 customer_name ),我们将基于此结果为他们推荐产品 C 。
您返回的查询结果需要按照 customer_id 排序

Customers 表:

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| customer_id         | int     |
| customer_name       | varchar |
+---------------------+---------+

customer_id 是这张表的主键。
customer_name 是顾客的名称。
 

Orders 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| customer_id   | int     |
| product_name  | varchar |
+---------------+---------+

order_id 是这张表的主键。
customer_id 是购买了名为 "product_name" 产品顾客的id。
 

请你设计 SQL 查询来报告购买了产品 A 和产品 B 却没有购买产品 C 的顾客的 ID 和姓名( customer_id 和 customer_name ),我们将基于此结果为他们推荐产品 C 。
您返回的查询结果需要按照 customer_id 排序。

 

查询结果如下例所示。

Customers table:

text
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1           | Daniel        |
| 2           | Diana         |
| 3           | Elizabeth     |
| 4           | Jhon          |
+-------------+---------------+

Orders table:

text
+------------+--------------+---------------+
| order_id   | customer_id  | product_name  |
+------------+--------------+---------------+
| 10         |     1        |     A         |
| 20         |     1        |     B         |
| 30         |     1        |     D         |
| 40         |     1        |     C         |
| 50         |     2        |     A         |
| 60         |     3        |     A         |
| 70         |     3        |     B         |
| 80         |     3        |     D         |
| 90         |     4        |     C         |
+------------+--------------+---------------+

Result table:

text
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 3           | Elizabeth     |
+-------------+---------------+

只有 customer_id 为 3 的顾客购买了产品 A 和产品 B ,却没有购买产品 C 。

sql
-- 嘻嘻,终于能实践一下having结合聚合函数来过滤了,简单题
//简化一下having having  sum(product_name='A') > 0 and sum(product_name='B') > 
//0 and sum(product_name='C') = 0
select
t1.customer_id,customer_name
from
Customers t1
join Orders t2 on t1.customer_id = t2.customer_id
group by t1.customer_id ,customer_name
having ( if(sum(product_name = "A") != 0,1,0) + if(sum(product_name = "B") != 0,1,0) + if(sum(product_name = "C") = 0,1,0) ) =3
order by t1.customer_id
sql
SELECT customer_id,customer_name 
FROM Customers 
WHERE 
customer_id IN(SELECT customer_id FROM Orders WHERE product_name='A') 
AND 
customer_id IN(SELECT customer_id FROM Orders WHERE product_name='B') 
AND 
customer_id NOT IN(SELECT customer_id FROM Orders WHERE product_name='C')

102.排名靠后的旅行者

写一段 SQL , 报告每个用户的旅行距离.
返回的结果表单,  以 travelled_distance 降序排列, 如果有两个或者更多的用户旅行了相同的距离, 那么再以 name 升序排列.

表单: Users

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+

id 是该表单主键.
name 是用户名字.
 

表单: Rides

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| user_id       | int     |
| distance      | int     |
+---------------+---------+

id 是该表单主键.
user_id 是本次行程的用户的 id, 而该用户此次行程距离为 distance.
 

写一段 SQL , 报告每个用户的旅行距离.

返回的结果表单,  以 travelled_distance 降序排列, 如果有两个或者更多的用户旅行了相同的距离, 那么再以 name 升序排列.

查询结果格式, 如下例所示.

 

Users 表单:

text
+------+-----------+
| id   | name      |
+------+-----------+
| 1    | Alice     |
| 2    | Bob       |
| 3    | Alex      |
| 4    | Donald    |
| 7    | Lee       |
| 13   | Jonathan  |
| 19   | Elvis     |
+------+-----------+

Rides 表单:

text
+------+----------+----------+
| id   | user_id  | distance |
+------+----------+----------+
| 1    | 1        | 120      |
| 2    | 2        | 317      |
| 3    | 3        | 222      |
| 4    | 7        | 100      |
| 5    | 13       | 312      |
| 6    | 19       | 50       |
| 7    | 7        | 120      |
| 8    | 19       | 400      |
| 9    | 7        | 230      |
+------+----------+----------+

Result 表单:

text
+----------+--------------------+
| name     | travelled_distance |
+----------+--------------------+
| Elvis    | 450                |
| Lee      | 450                |
| Bob      | 317                |
| Jonathan | 312                |
| Alex     | 222                |
| Alice    | 120                |
| Donald   | 0                  |
+----------+--------------------+

Elvis 和 Lee 旅行了 450 英里, Elvis 是排名靠前的旅行者, 因为他的名字在字母表上的排序比 Lee 更小.
Bob, Jonathan, Alex 和 Alice 只有一次行程, 我们只按此次行程的全部距离对他们排序.
Donald 没有任何行程, 他的旅行距离为 0.

sql
-- 简单题
select
max(name) as name ,
ifnull(sum(distance),0) travelled_distance
from 
Users t1
left join Rides t2 on t1.id = t2.user_id
group by t1.id 
order by travelled_distance desc ,name 
sql
为什么这个不报错?name不是聚合有的哇
select u.name, sum(ifnull(r.distance, 0)) as travelled_distance
from Users as u left join Rides as r on u.id = r.user_id
group by u.id
order by travelled_distance desc, u.name

103.查询成绩处于中游的学生

成绩处于中游的学生是指至少参加了一次测验, 且得分既不是最高分也不是最低分的学生
写一个 SQL 语句,找出在所有测验中都处于中游的学生 (student_id, student_name)
不要返回从来没有参加过测验的学生。返回结果表按照 student_id 排序

表: Student

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| student_id          | int     |
| student_name        | varchar |
+---------------------+---------+

student_id 是该表主键.
student_name 学生名字.
 

表: Exam

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| exam_id       | int     |
| student_id    | int     |
| score         | int     |
+---------------+---------+

(exam_id, student_id) 是该表主键.
学生 student_id 在测验 exam_id 中得分为 score.
 

成绩处于中游的学生是指至少参加了一次测验, 且得分既不是最高分也不是最低分的学生。

写一个 SQL 语句,找出在所有测验中都处于中游的学生 (student_id, student_name)。

不要返回从来没有参加过测验的学生。返回结果表按照 student_id 排序。

查询结果格式如下。

 

Student 表:

text
+-------------+---------------+
| student_id  | student_name  |
+-------------+---------------+
| 1           | Daniel        |
| 2           | Jade          |
| 3           | Stella        |
| 4           | Jonathan      |
| 5           | Will          |
+-------------+---------------+

Exam 表:

text
+------------+--------------+-----------+
| exam_id    | student_id   | score     |
+------------+--------------+-----------+
| 10         |     1        |    70     |
| 10         |     2        |    80     |
| 10         |     3        |    90     |
| 20         |     1        |    80     |
| 30         |     1        |    70     |
| 30         |     3        |    80     |
| 30         |     4        |    90     |
| 40         |     1        |    60     |
| 40         |     2        |    70     |
| 40         |     4        |    80     |
+------------+--------------+-----------+

Result 表:

text
+-------------+---------------+
| student_id  | student_name  |
+-------------+---------------+
| 2           | Jade          |
+-------------+---------------+

对于测验 1: 学生 1 和 3 分别获得了最低分和最高分。
对于测验 2: 学生 1 既获得了最高分, 也获得了最低分。
对于测验 3 和 4: 学生 1 和 4 分别获得了最低分和最高分。
学生 2 和 5 没有在任一场测验中获得了最高分或者最低分。
因为学生 5 从来没有参加过任何测验, 所以他被排除于结果表。
由此, 我们仅仅返回学生 2 的信息。

sql
--执行错误??,发现问题把row_number该为rank.....检查了好久
select
distinct Student.student_id,student_name 
from 
Student join Exam on Student.student_id = Exam.student_id 
where (Student.student_id,student_name) not in (
select
distinct student_id,student_name 
from 
(
select
Student.student_id,student_name,
rank() over(partition by exam_id order by score desc ) as max_rn,
rank() over(partition by exam_id order by score asc ) as min_rn
from
Student
join Exam on Student.student_id = Exam.student_id
) t1
where max_rn = 1 or min_rn = 1 )
order by Student.student_id asc
sql
with cte as (
select distinct student_id
from (select exam_id,
      student_id,
      rank() over (partition by exam_id order by score desc) as r1,
      rank() over (partition by exam_id order by score asc) as r2
      from exam) as temp
where r1 = 1 or r2 = 1)
select
distinct Student.student_id,student_name 
from 
Student join Exam on Student.student_id = Exam.student_id 
where Student.student_id not in ( select student_id from cte)
order by Student.student_id asc;

使用max和min开窗来获取每组的最值情况也可以

sql
--非窗口写法
select e.student_id, s.student_name
from
    (select exam_id, max(score) s1, min(score) s2
    from exam group by exam_id) t, exam e, student s 
where t.exam_id = e.exam_id and e.student_id = s.student_id
group by e.student_id
having count(*) = sum(e.score>s2 and e.score<s1)
order by e.student_id;

104.净现值查询

写一个 SQL, 找到 Queries 表中每一次查询的净现值

表: NPV

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| year          | int     |
| npv           | int     |
+---------------+---------+

(id, year) 是该表主键.
该表有每一笔存货的年份, id 和对应净现值的信息.
 

表: Queries

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| year          | int     |
+---------------+---------+

(id, year) 是该表主键.
该表有每一次查询所对应存货的 id 和年份的信息.
 

写一个 SQL, 找到 Queries 表中每一次查询的净现值.

结果表没有顺序要求.

查询结果的格式如下所示:

NPV 表:

text
+------+--------+--------+
| id   | year   | npv    |
+------+--------+--------+
| 1    | 2018   | 100    |
| 7    | 2020   | 30     |
| 13   | 2019   | 40     |
| 1    | 2019   | 113    |
| 2    | 2008   | 121    |
| 3    | 2009   | 12     |
| 11   | 2020   | 99     |
| 7    | 2019   | 0      |
+------+--------+--------+

Queries 表:

text
+------+--------+
| id   | year   |
+------+--------+
| 1    | 2019   |
| 2    | 2008   |
| 3    | 2009   |
| 7    | 2018   |
| 7    | 2019   |
| 7    | 2020   |
| 13   | 2019   |
+------+--------+

结果表:

text
+------+--------+--------+
| id   | year   | npv    |
+------+--------+--------+
| 1    | 2019   | 113    |
| 2    | 2008   | 121    |
| 3    | 2009   | 12     |
| 7    | 2018   | 0      |
| 7    | 2019   | 0      |
| 7    | 2020   | 30     |
| 13   | 2019   | 40     |
+------+--------+--------+

(7, 2018)的净现值不在 NPV 表中, 我们把它看作是 0.
所有其它查询的净现值都能在 NPV 表中找到.

sql
--简单题
select 
t1.id,t1.year,ifnull(npv,0) as npv 
from 
Queries t1
left join NPV t2 on t1.id =t2.id and t1.year = t2.year

105.制作会话柱状图

你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>" 和 "15 or more" (单位:分钟)的会话数量,并以此绘制柱状图
写一个SQL查询来报告(访问时长区间,会话总数)。结果可用任何顺序呈现

表:Sessions

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| session_id          | int     |
| duration            | int     |
+---------------------+---------+

session_id 是该表主键
duration 是用户访问应用的时间, 以秒为单位
 

你想知道用户在你的 app 上的访问时长情况。因此决定统计访问时长区间分别为 "[0-5>", "[5-10>", "[10-15>" 和 "15 or more" (单位:分钟)的会话数量,并以此绘制柱状图。

写一个SQL查询来报告(访问时长区间,会话总数)。结果可用任何顺序呈现。

 

下方为查询的输出格式:

Sessions 表:

text
+-------------+---------------+
| session_id  | duration      |
+-------------+---------------+
| 1           | 30            |
| 2           | 199           |
| 3           | 299           |
| 4           | 580           |
| 5           | 1000          |
+-------------+---------------+

Result 表:

text
+--------------+--------------+
| bin          | total        |
+--------------+--------------+
| [0-5>        | 3            |
| [5-10>       | 1            |
| [10-15>      | 0            |
| 15 or more   | 1            |
+--------------+--------------+

对于 session_id 1,2 和 3 ,它们的访问时间大于等于 0 分钟且小于 5 分钟。
对于 session_id 4,它的访问时间大于等于 5 分钟且小于 10 分钟。
没有会话的访问时间大于等于 10 分钟且小于 15 分钟。
对于 session_id 5, 它的访问时间大于等于 15 分钟。

sql
--我的写法,怎么改进一下
select
"[0-5>" as bin ,sum(if(duration/60 >=0 and duration/60 <5,1,0)) as total 
from
Sessions
union all 
(
select
"[5-10>"  ,sum(if(duration/60 >=5 and duration/60 <10,1,0) )
from
Sessions
)

union all 
(
select
"[10-15>"  ,sum(if(duration/60 >=10 and duration/60 <15,1,0) )
from
Sessions
)
union all 
(
select
"15 or more"  ,sum(if(duration/60 >=15 ,1,0) )
from
Sessions
)

解法1

sql
select derived2.bin,ifnull(derived1.total,0) as total 
from

返回每个区间的计数

sql
(
	select 
		case
			when duration/60<5 then '[0-5>'
			when duration/60<10 then '[5-10>'
			when duration/60<15 then '[10-15>'
			else '15 or more'
		end bin,
		count(*) total
	from Sessions
	group by bin

) as derived1

构建区间表

sql
right join 
(
	select '[0-5>' as bin 
			union
	select '[5-10>' as bin 
			union
	select '[10-15>' as bin 
			union
	select '15 or more' as bin
     
)derived2

on derived2.bin = derived1.bin

解法2

sql
select '[0-5>' bin, count(*) as total from Sessions where floor(duration/(60*5))=0
union
select '[5-10>' bin, count(*) as total from Sessions where floor(duration/(60*5))=1 
union
select '[10-15>' bin, count(*) as total from Sessions where floor(duration/(60*5))=2
union
select '15 or more' bin, count(*) as total from Sessions where floor(duration/(60*5))>=3
order by bin

解法3

sql
select '[0-5>' BIN, sum(if(duration<300,1,0)) TOTAL from Sessions 
union 
select '[5-10>' bin, sum(if(300<=duration and duration<600,1,0)) total from Sessions
union 
select '[10-15>' bin, sum(if(600<=duration and duration<900,1,0)) total from Sessions 
union 
select '15 or more' bin, sum(if(900<=duration,1,0)) total from Sessions 

106.计算布尔表达式的值(等量代换)☆

写一个 SQL 查询, 以计算表 Expressions 中的布尔表达式

表 Variables:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| name          | varchar |
| value         | int     |
+---------------+---------+

name 是该表主键.
该表包含了存储的变量及其对应的值.
 

表 Expressions:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| left_operand  | varchar |
| operator      | enum    |
| right_operand | varchar |
+---------------+---------+

(left_operand, operator, right_operand) 是该表主键.
该表包含了需要计算的布尔表达式.
operator 是枚举类型, 取值于('<', '>', '=')
left_operand 和 right_operand 的值保证存在于 Variables 表单中.
 

写一个 SQL 查询,  以计算表 Expressions 中的布尔表达式.

返回的结果表没有顺序要求.

查询结果格式如下例所示.

Variables 表:

text
+------+-------+
| name | value |
+------+-------+
| x    | 66    |
| y    | 77    |
+------+-------+

Expressions 表:

text
+--------------+----------+---------------+
| left_operand | operator | right_operand |
+--------------+----------+---------------+
| x            | >        | y             |
| x            | <        | y             |
| x            | =        | y             |
| y            | >        | x             |
| y            | <        | x             |
| x            | =        | x             |
+--------------+----------+---------------+

Result 表:

text
+--------------+----------+---------------+-------+
| left_operand | operator | right_operand | value |
+--------------+----------+---------------+-------+
| x            | >        | y             | false |
| x            | <        | y             | true  |
| x            | =        | y             | false |
| y            | >        | x             | true  |
| y            | <        | x             | false |
| x            | =        | x             | true  |
+--------------+----------+---------------+-------+

如上所示, 你需要通过使用 Variables 表来找到 Expressions 表中的每一个布尔表达式的值

sql
--难题,我的解决方法就是casewhen 判断怎么优化一下?
select e.*,
    case
        when operator = '=' and v1.value = v2.value then 'true'
        when operator = '>' and v1.value > v2.value then 'true'
        when operator = '<' and v1.value < v2.value then 'true'
        else 'false'
    end value
from Expressions e
left join Variables v1
on e.left_operand = v1.name
left join Variables v2
on e.right_operand = v2.name

学习一招---等量代换用join来实现

107.苹果与橘子

写一个 SQL 查询, 报告每一天 苹果 和 桔子 销售的数目的差异.
返回的结果表, 按照格式为 ('YYYY-MM-DD') 的 sale_date 排序.

表: Sales

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| sale_date     | date    |
| fruit         | enum    | 
| sold_num      | int     | 
+---------------+---------+

(sale_date,fruit) 是该表主键.
该表包含了每一天中"苹果" 和 "桔子"的销售情况.
 

写一个 SQL 查询, 报告每一天 苹果 和 桔子 销售的数目的差异.

返回的结果表, 按照格式为 ('YYYY-MM-DD') 的 sale_date 排序.

查询结果表如下例所示:

 

Sales 表:

text
+------------+------------+-------------+
| sale_date  | fruit      | sold_num    |
+------------+------------+-------------+
| 2020-05-01 | apples     | 10          |
| 2020-05-01 | oranges    | 8           |
| 2020-05-02 | apples     | 15          |
| 2020-05-02 | oranges    | 15          |
| 2020-05-03 | apples     | 20          |
| 2020-05-03 | oranges    | 0           |
| 2020-05-04 | apples     | 15          |
| 2020-05-04 | oranges    | 16          |
+------------+------------+-------------+

Result 表:

text
+------------+--------------+
| sale_date  | diff         |
+------------+--------------+
| 2020-05-01 | 2            |
| 2020-05-02 | 0            |
| 2020-05-03 | 20           |
| 2020-05-04 | -1           |
+------------+--------------+

在 2020-05-01, 卖了 10 个苹果 和 8 个桔子 (差异为 10 - 8 = 2).
在 2020-05-02, 卖了 15 个苹果 和 15 个桔子 (差异为 15 - 15 = 0).
在 2020-05-03, 卖了 20 个苹果 和 0 个桔子 (差异为 20 - 0 = 20).
在 2020-05-04, 卖了 15 个苹果 和 16 个桔子 (差异为 15 - 16 = -1).

sql
--简单题
select
sale_date,
sum(if(fruit ="apples",sold_num,0)) - sum(if(fruit ="oranges",sold_num,0)) diff
from
Sales
group by sale_date
sql
--学习一下,忘记了...
SELECT sale_date, SUM(case when fruit='apples' then sold_num else -sold_num end) as diff
FROM Sales
GROUP BY sale_date
ORDER BY sale_date

108.活跃用户

写一个 SQL 查询, 找到活跃用户的 id 和 name.
活跃用户是指那些至少连续 5 天登录账户的用户.

表 Accounts:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+

id 是该表主键.
该表包含账户 id 和账户的用户名.
 

表 Logins:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| login_date    | date    |
+---------------+---------+

该表无主键, 可能包含重复项.
该表包含登录用户的账户 id 和登录日期. 用户也许一天内登录多次.
 

写一个 SQL 查询,  找到活跃用户的 id 和 name.

活跃用户是指那些至少连续 5 天登录账户的用户.

返回的结果表按照 id 排序.

结果表格式如下例所示:

Accounts 表:

text
+----+----------+
| id | name     |
+----+----------+
| 1  | Winston  |
| 7  | Jonathan |
+----+----------+

Logins 表:

text
+----+------------+
| id | login_date |
+----+------------+
| 7  | 2020-05-30 |
| 1  | 2020-05-30 |
| 7  | 2020-05-31 |
| 7  | 2020-06-01 |
| 7  | 2020-06-02 |
| 7  | 2020-06-02 |
| 7  | 2020-06-03 |
| 1  | 2020-06-07 |
| 7  | 2020-06-10 |
+----+------------+

Result 表:

text
+----+----------+
| id | name     |
+----+----------+
| 7  | Jonathan |
+----+----------+

id = 1 的用户 Winston 仅仅在不同的 2 天内登录了 2 次, 所以, Winston 不是活跃用户
id = 7 的用户 Jonathon 在不同的 6 天内登录了 7 次, , 6 天中有 5 天是连续的, 所以, Jonathan 是活跃用户

sql
--简答题
select
distinct t3.id,name 
from
(
select
id 
from 
(
select
id,
date_sub(login_date,INTERVAL dense_rank() over(partition by id order by login_date ) DAY ) x1
from
(
select
distinct id,login_date 
from 
Logins
) t1
) t2
group by id,x1
having count(1) >= 5
) t3
join Accounts on t3.id = Accounts.id 
order by t3.id 
sql
select distinct a.id, a.name
from Accounts a
join
(select * ,lead(s.login_date,4) over(partition by s.id order by s.login_date asc) as last_date
 from (select distinct id, login_date from Logins) s
)t
on a.id = t.id
where datediff(t.login_date, t.last_date) = -4
order by a.id

109.矩形面积

写一个 SQL 语句, 报告由表中任意两点可以形成的所有可能的矩形

表: Points

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| x_value       | int     |
| y_value       | int     |
+---------------+---------+

id 是该表主键.
每个点都表示为二维空间 (x_value, y_value).
写一个 SQL 语句, 报告由表中任意两点可以形成的所有可能的矩形. 

结果表中的每一行包含三列 (p1, p2, area) 如下:

p1 和 p2 是矩形两个对角的 id 且 p1 < p2.
矩形的面积由列 area 表示. 
请按照面积大小降序排列,如果面积相同的话, 则按照 p1 和 p2 升序对结果表排序

Points 表:

text
+----------+-------------+-------------+
| id       | x_value     | y_value     |
+----------+-------------+-------------+
| 1        | 2           | 8           |
| 2        | 4           | 7           |
| 3        | 2           | 10          |
+----------+-------------+-------------+

Result 表:

text
+----------+-------------+-------------+
| p1       | p2          | area        |
+----------+-------------+-------------+
| 2        | 3           | 6           |
| 1        | 2           | 2           |
+----------+-------------+-------------+

p1 应该小于 p2 并且面积大于 0.
p1 = 1 且 p2 = 2 时, 面积等于 |2-4| * |8-7| = 2.
p1 = 2 且 p2 = 3 时, 面积等于 |4-2| * |7-10| = 6.
p1 = 1 且 p2 = 3 时, 是不可能为矩形的, 因为面积等于 0.

sql
--理解错题意了写了半天,id是对角id?
select
distinct  p1,p2,area 
from 
(
select
if(abs(t1.x_value - t2.x_value)>=abs(t1.y_value - t2.y_value),abs(t1.y_value - t2.y_value),abs(t1.x_value - t2.x_value)) p1, 
if(abs(t1.x_value - t2.x_value)<=abs(t1.y_value - t2.y_value),abs(t1.y_value - t2.y_value),abs(t1.x_value - t2.x_value)) p2,
abs(t1.x_value - t2.x_value) * abs(t1.y_value - t2.y_value) as area 
from
Points t1
cross join Points t2
) s1
where area > 0
order by area desc,p1 desc,p2 desc 
sql
--简单题,优化一下直接 where p1.id<p2.id 判断
select
distinct  p1,p2,area 
from 
(
select
if(t1.id>=t2.id,t2.id,t1.id) as p1,
if(t1.id<=t2.id,t2.id,t1.id) as p2,
abs(t1.x_value - t2.x_value) * abs(t1.y_value - t2.y_value) as area 
from
Points t1
cross join Points t2
) s1
where area > 0
order by area desc,p1 ,p2

110.计算税后工资

写一条查询 SQL 来查找每个员工的税后工资
每个公司的税率计算依照以下规则
如果这个公司员工最高工资不到 1000 ,税率为 0%
如果这个公司员工最高工资在 1000 到 10000 之间,税率为 24%
如果这个公司员工最高工资大于 10000 ,税率为 49%

Salaries 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| company_id    | int     |
| employee_id   | int     |
| employee_name | varchar |
| salary        | int     |
+---------------+---------+

(company_id, employee_id) 是这个表的主键
这个表包括员工的company id, id, name 和 salary
 

写一条查询 SQL 来查找每个员工的税后工资

每个公司的税率计算依照以下规则

如果这个公司员工最高工资不到 1000 ,税率为 0%
如果这个公司员工最高工资在 1000 到 10000 之间,税率为 24%
如果这个公司员工最高工资大于 10000 ,税率为 49%
按任意顺序返回结果,税后工资结果取整

 

结果表格式如下例所示:

Salaries 表:

text
+------------+-------------+---------------+--------+
| company_id | employee_id | employee_name | salary |
+------------+-------------+---------------+--------+
| 1          | 1           | Tony          | 2000   |
| 1          | 2           | Pronub        | 21300  |
| 1          | 3           | Tyrrox        | 10800  |
| 2          | 1           | Pam           | 300    |
| 2          | 7           | Bassem        | 450    |
| 2          | 9           | Hermione      | 700    |
| 3          | 7           | Bocaben       | 100    |
| 3          | 2           | Ognjen        | 2200   |
| 3          | 13          | Nyancat       | 3300   |
| 3          | 15          | Morninngcat   | 7777   |
+------------+-------------+---------------+--------+

Result 表:

text
+------------+-------------+---------------+--------+
| company_id | employee_id | employee_name | salary |
+------------+-------------+---------------+--------+
| 1          | 1           | Tony          | 1020   |
| 1          | 2           | Pronub        | 10863  |
| 1          | 3           | Tyrrox        | 5508   |
| 2          | 1           | Pam           | 300    |
| 2          | 7           | Bassem        | 450    |
| 2          | 9           | Hermione      | 700    |
| 3          | 7           | Bocaben       | 76     |
| 3          | 2           | Ognjen        | 1672   |
| 3          | 13          | Nyancat       | 2508   |
| 3          | 15          | Morninngcat   | 5911   |
+------------+-------------+---------------+--------+

对于公司 1 ,最高工资是 21300 ,其每个员工的税率为 49%
对于公司 2 ,最高工资是 700 ,其每个员工税率为 0%
对于公司 3 ,最高工资是 7777 ,其每个员工税率是 24%
税后工资计算 = 工资 - ( 税率 / 100)*工资
对于上述案例,Morninngcat 的税后工资 = 7777 - 7777 * ( 24 / 100) = 7777 - 1866.48 = 5910.52 ,取整为 5911

sql
--简单题,可以一步完成在case when 中使用窗口函数
select 
company_id,
employee_id,
employee_name,
round(
case 
when max_salary <1000 then salary 
when max_salary > 10000 then salary - salary * ( 49 / 100) 
else salary - salary * ( 24 / 100)  end )  as salary
from 
(
select
company_id,
employee_id,
employee_name,
salary,
max(salary) over(partition by company_id) as max_salary
from
Salaries
) temp 
sql
with tax as
(select company_id, case when max(salary) < 1000 then 0 
                        when max(salary) between 1000 and 10000 then 0.24
                        else 0.49 end as tax_rate
from salaries
group by company_id)

select s.company_id, s.employee_id, s.employee_name, round(s.salary * (1-tax_rate),0) as salary
from salaries s join tax t on s.company_id = t.company_id

练习题 11

111.周内的每天销售情况

写一个SQL语句,报告 周内每天 每个商品类别下订购了多少单位

表:Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| customer_id   | int     |
| order_date    | date    | 
| item_id       | varchar |
| quantity      | int     |
+---------------+---------+

(order_id, item_id) 是该表主键
该表包含了订单信息
order_date 是id为 item_id 的商品被id为 customer_id 的消费者订购的日期.
表:Items

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| item_id             | varchar |
| item_name           | varchar |
| item_category       | varchar |
+---------------------+---------+

item_id 是该表主键
item_name 是商品的名字
item_category 是商品的类别
 

你是企业主,想要获得分类商品和周内每天的销售报告。

写一个SQL语句,报告 周内每天 每个商品类别下订购了多少单位。

返回结果表单 按商品类别排序 。

查询结果格式如下例所示:

 

Orders 表:

text
+------------+--------------+-------------+--------------+-------------+
| order_id   | customer_id  | order_date  | item_id      | quantity    |
+------------+--------------+-------------+--------------+-------------+
| 1          | 1            | 2020-06-01  | 1            | 10          |
| 2          | 1            | 2020-06-08  | 2            | 10          |
| 3          | 2            | 2020-06-02  | 1            | 5           |
| 4          | 3            | 2020-06-03  | 3            | 5           |
| 5          | 4            | 2020-06-04  | 4            | 1           |
| 6          | 4            | 2020-06-05  | 5            | 5           |
| 7          | 5            | 2020-06-05  | 1            | 10          |
| 8          | 5            | 2020-06-14  | 4            | 5           |
| 9          | 5            | 2020-06-21  | 3            | 5           |
+------------+--------------+-------------+--------------+-------------+

Items 表:

text
+------------+----------------+---------------+
| item_id    | item_name      | item_category |
+------------+----------------+---------------+
| 1          | LC Alg. Book   | Book          |
| 2          | LC DB. Book    | Book          |
| 3          | LC SmarthPhone | Phone         |
| 4          | LC Phone 2020  | Phone         |
| 5          | LC SmartGlass  | Glasses       |
| 6          | LC T-Shirt XL  | T-Shirt       |
+------------+----------------+---------------+

Result 表:

text
+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
| Category   | Monday    | Tuesday   | Wednesday | Thursday  | Friday    | Saturday  | Sunday    |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+
| Book       | 20        | 5         | 0         | 0         | 10        | 0         | 0         |
| Glasses    | 0         | 0         | 0         | 0         | 5         | 0         | 0         |
| Phone      | 0         | 0         | 5         | 1         | 0         | 0         | 10        |
| T-Shirt    | 0         | 0         | 0         | 0         | 0         | 0         | 0         |
+------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+

在周一(2020-06-01, 2020-06-08),Book分类(ids: 1, 2)下,总共销售了20个单位(10 + 10)
在周二(2020-06-02),Book分类(ids: 1, 2)下,总共销售了5个单位
在周三(2020-06-03),Phone分类(ids: 3, 4)下,总共销售了5个单位
在周四(2020-06-04),Phone分类(ids: 3, 4)下,总共销售了1个单位
在周五(2020-06-05),Book分类(ids: 1, 2)下,总共销售了10个单位,Glasses分类(ids: 5)下,总共销售了5个单位
在周六, 没有商品销售
在周天(2020-06-14, 2020-06-21),Phone分类(ids: 3, 4)下,总共销售了10个单位(5 + 5)
没有销售 T-Shirt 类别的商品

sql
--简单题,注意怎么获取星期几,以及星期天是星期的第一天
//weekday dayname的使用
select
item_category Category,
ifnull(sum(if(date_format(order_date,"%w")=1,quantity ,0)),0) Monday ,
ifnull(sum(if(date_format(order_date,"%w")=2,quantity ,0)),0) Tuesday  ,
ifnull(sum(if(date_format(order_date,"%w")=3,quantity ,0)),0) Wednesday ,
ifnull(sum(if(date_format(order_date,"%w")=4,quantity ,0)),0) Thursday  ,
ifnull(sum(if(date_format(order_date,"%w")=5,quantity ,0)),0) Friday  ,
ifnull(sum(if(date_format(order_date,"%w")=6,quantity ,0)),0) Saturday  ,
ifnull(sum(if(date_format(order_date,"%w")=0,quantity ,0)),0) Sunday  
from 
Items t1 left join Orders t2 on  t1.item_id = t2.item_id
group by item_category
order by item_category

112.按日期分组销售产品(group_concat)

编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。
每个日期的销售产品名称应按词典序排列。
返回按 sell_date 排序的结果表。

表 Activities:

text
+-------------+---------+
| 列名         | 类型    |
+-------------+---------+
| sell_date   | date    |
| product     | varchar |
+-------------+---------+

此表没有主键,它可能包含重复项。
此表的每一行都包含产品名称和在市场上销售的日期。
 

编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。
每个日期的销售产品名称应按词典序排列。
返回按 sell_date 排序的结果表。

查询结果格式如下例所示。

Activities 表:

text
+------------+-------------+
| sell_date  | product     |
+------------+-------------+
| 2020-05-30 | Headphone   |
| 2020-06-01 | Pencil      |
| 2020-06-02 | Mask        |
| 2020-05-30 | Basketball  |
| 2020-06-01 | Bible       |
| 2020-06-02 | Mask        |
| 2020-05-30 | T-Shirt     |
+------------+-------------+

Result 表:

text
+------------+----------+------------------------------+
| sell_date  | num_sold | products                     |
+------------+----------+------------------------------+
| 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2        | Bible,Pencil                 |
| 2020-06-02 | 1        | Mask                         |
+------------+----------+------------------------------+

对于2020-05-30,出售的物品是 (Headphone, Basketball, T-shirt),按词典序排列,并用逗号 ',' 分隔。
对于2020-06-01,出售的物品是 (Pencil, Bible),按词典序排列,并用逗号分隔。
对于2020-06-02,出售的物品是 (Mask),只需返回该物品名。

sql
--难题,没用过group_concat函数,注意取别名类似于hive中的炸裂函数
select
sell_date,count(distinct product) num_sold,
group_concat(distinct product separator ",") products 
from 
(
select
sell_date,product
from
Activities a 
order by sell_date,product
) t1
group by sell_date
order  by sell_date
sql
--注意也可以在函数中直接排序
select sell_date, count(distinct product) num_sold,
group_concat(distinct product order by product asc separator ',') as products
from activities
group by sell_date

113.上月播放的儿童适宜电影

写一个 SQL 语句, 报告在 2020 年 6 月份播放的儿童适宜电影的去重电影名

表: TVProgram

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| program_date  | date    |
| content_id    | int     |
| channel       | varchar |
+---------------+---------+

(program_date, content_id) 是该表主键.
该表包含电视上的节目信息.
content_id 是电视一些频道上的节目的 id.
 

表: Content

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| content_id       | varchar |
| title            | varchar |
| Kids_content     | enum    |
| content_type     | varchar |
+------------------+---------+

content_id 是该表主键.
Kids_content 是枚举类型, 取值为('Y', 'N'), 其中:
'Y' 表示儿童适宜内容, 而'N'表示儿童不宜内容.
content_type 表示内容的类型, 比如电影, 电视剧等.
 

写一个 SQL 语句,  报告在 2020 年 6 月份播放的儿童适宜电影的去重电影名.

返回的结果表单没有顺序要求.

查询结果的格式如下例所示.

 

TVProgram 表:

text
+--------------------+--------------+-------------+
| program_date       | content_id   | channel     |
+--------------------+--------------+-------------+
| 2020-06-10 08:00   | 1            | LC-Channel  |
| 2020-05-11 12:00   | 2            | LC-Channel  |
| 2020-05-12 12:00   | 3            | LC-Channel  |
| 2020-05-13 14:00   | 4            | Disney Ch   |
| 2020-06-18 14:00   | 4            | Disney Ch   |
| 2020-07-15 16:00   | 5            | Disney Ch   |
+--------------------+--------------+-------------+

Content 表:

text
+------------+----------------+---------------+---------------+
| content_id | title          | Kids_content  | content_type  |
+------------+----------------+---------------+---------------+
| 1          | Leetcode Movie | N             | Movies        |
| 2          | Alg. for Kids  | Y             | Series        |
| 3          | Database Sols  | N             | Series        |
| 4          | Aladdin        | Y             | Movies        |
| 5          | Cinderella     | Y             | Movies        |
+------------+----------------+---------------+---------------+

Result 表:

text
+--------------+
| title        |
+--------------+
| Aladdin      |
+--------------+

"Leetcode Movie" 是儿童不宜的电影.
"Alg. for Kids" 不是电影.
"Database Sols" 不是电影
"Alladin" 是电影, 儿童适宜, 并且在 2020 年 6 月份播放.
"Cinderella" 不在 2020 年 6 月份播放

sql
--简单题,注意使用like要加%的使用
select
distinct title
from
(
select
content_id 
from  
TVProgram t1
where program_date like "2020-06%"
) t1 
join 
(
select
content_id, title 
from  
Content
where  content_type = "Movies"  and Kids_content = "Y"
) t2 on t1.content_id = t2.content_id
sql
select title from content 
where kids_content = "Y" and content_type = "Movies" 
and content_id in
(select content_id from tvprogram where program_date like "2020-06%")

注意查询枚举类型的效率问题

114.可以放心投资的国家(总体平均值)

一家电信公司想要投资新的国家. 该公司想要投资的国家是:  该国的平均通话时长要严格地大于全球平均通话时长
写一段 SQL,  找到所有该公司可以投资的国家

表 Person:

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| id             | int     |
| name           | varchar |
| phone_number   | varchar |
+----------------+---------+

id 是该表主键.
该表每一行包含一个人的名字和电话号码.
电话号码的格式是:'xxx-yyyyyyy', 其中xxx是国家码(3个字符), yyyyyyy是电话号码(7个字符), x和y都表示数字. 同时, 国家码和电话号码都可以包含前导0.
表 Country:

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| name           | varchar |
| country_code   | varchar |
+----------------+---------+

country_code是该表主键.
该表每一行包含国家名和国家码. country_code的格式是'xxx', x是数字.
 

表 Calls:

text
+-------------+------+
| Column Name | Type |
+-------------+------+
| caller_id   | int  |
| callee_id   | int  |
| duration    | int  |
+-------------+------+

该表无主键, 可能包含重复行.
每一行包含呼叫方id, 被呼叫方id和以分钟为单位的通话时长. caller_id != callee_id
一家电信公司想要投资新的国家. 该公司想要投资的国家是:  该国的平均通话时长要严格地大于全球平均通话时长.

写一段 SQL,  找到所有该公司可以投资的国家.

返回的结果表没有顺序要求.

查询的结果格式如下例所示.

Person 表:

text
+----+----------+--------------+
| id | name     | phone_number |
+----+----------+--------------+
| 3  | Jonathan | 051-1234567  |
| 12 | Elvis    | 051-7654321  |
| 1  | Moncef   | 212-1234567  |
| 2  | Maroua   | 212-6523651  |
| 7  | Meir     | 972-1234567  |
| 9  | Rachel   | 972-0011100  |
+----+----------+--------------+

Country 表:

text
+----------+--------------+
| name     | country_code |
+----------+--------------+
| Peru     | 051          |
| Israel   | 972          |
| Morocco  | 212          |
| Germany  | 049          |
| Ethiopia | 251          |
+----------+--------------+

Calls 表:

text
+-----------+-----------+----------+
| caller_id | callee_id | duration |
+-----------+-----------+----------+
| 1         | 9         | 33       |
| 2         | 9         | 4        |
| 1         | 2         | 59       |
| 3         | 12        | 102      |
| 3         | 12        | 330      |
| 12        | 3         | 5        |
| 7         | 9         | 13       |
| 7         | 1         | 3        |
| 9         | 7         | 1        |
| 1         | 7         | 7        |
+-----------+-----------+----------+

Result 表:

text
+----------+
| country  |
+----------+
| Peru     |
+----------+

国家Peru的平均通话时长是 (102 + 102 + 330 + 330 + 5 + 5) / 6 = 145.666667
国家Israel的平均通话时长是 (33 + 4 + 13 + 13 + 3 + 1 + 1 + 7) / 8 = 9.37500
国家Morocco的平均通话时长是 (33 + 4 + 59 + 59 + 3 + 7) / 6 = 27.5000
全球平均通话时长 = (2 * (33 + 3 + 59 + 102 + 330 + 5 + 13 + 3 + 1 + 7)) / 20 = 55.70000
所以, Peru是唯一的平均通话时长大于全球平均通话时长的国家, 也是唯一的推荐投资的国家.

sql
--简单题,我写的麻烦,看了下评论区事实上求总体的平均值只需要对表avg即可,不需要union all.....
with x as (
select
name,id 
from
Country t1
left join 
(
select
id,left(phone_number,3) as country_code
from
Person 
) t2 on t1.country_code = t2.country_code ) 

select
distinct name  country 
from 
(
select
name,
avg(duration) over(partition by name ) as avg_1,
avg(duration) over() as avg_2  
from
( 
select
name,duration
from  
Calls
join x on Calls.caller_id = x.id
union all 
(
select
name,duration 
from 
Calls
join x on Calls.callee_id  = x.id    
) 
) s2 
) s3
where avg_1 > avg_2
sql
with cte as (
select ct.name, avg(cl.duration) as avg_country
from person a 
       join country ct on left(a.phone_number, 3)=ct.country_code
       join calls cl on a.id=cl.caller_id or a.id=cl.callee_id
group by ct.name)
select name as country
from cte
where avg_country > (select avg(duration) from calls)

注意在join中使用 or ....这样就不需要union all了...

115.消费者下单频率

写一个 SQL 语句, 报告消费者的 id 和名字, 其中消费者在 2020 年 6 月和 7 月, 每月至少花费了$100.

表: Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
| country       | varchar |
+---------------+---------+

customer_id 是该表主键.
该表包含公司消费者的信息.
 

表: Product

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| description   | varchar |
| price         | int     |
+---------------+---------+

product_id 是该表主键.
该表包含公司产品的信息.
price 是本产品的花销.
 

表: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| customer_id   | int     |
| product_id    | int     |
| order_date    | date    |
| quantity      | int     |
+---------------+---------+

order_id 是该表主键.
该表包含消费者下单的信息.
customer_id 是买了数量为"quantity", id为"product_id"产品的消费者的 id.
Order_date 是订单发货的日期, 格式为('YYYY-MM-DD').
 

写一个 SQL 语句,  报告消费者的 id 和名字, 其中消费者在 2020 年 6 月和 7 月, 每月至少花费了$100.

结果表无顺序要求.

查询结果格式如下例所示.

 

Customers

text
+--------------+-----------+-------------+
| customer_id  | name      | country     |
+--------------+-----------+-------------+
| 1            | Winston   | USA         |
| 2            | Jonathan  | Peru        |
| 3            | Moustafa  | Egypt       |
+--------------+-----------+-------------+

Product

text
+--------------+-------------+-------------+
| product_id   | description | price       |
+--------------+-------------+-------------+
| 10           | LC Phone    | 300         |
| 20           | LC T-Shirt  | 10          |
| 30           | LC Book     | 45          |
| 40           | LC Keychain | 2           |
+--------------+-------------+-------------+

Orders

text
+--------------+-------------+-------------+-------------+-----------+
| order_id     | customer_id | product_id  | order_date  | quantity  |
+--------------+-------------+-------------+-------------+-----------+
| 1            | 1           | 10          | 2020-06-10  | 1         |
| 2            | 1           | 20          | 2020-07-01  | 1         |
| 3            | 1           | 30          | 2020-07-08  | 2         |
| 4            | 2           | 10          | 2020-06-15  | 2         |
| 5            | 2           | 40          | 2020-07-01  | 10        |
| 6            | 3           | 20          | 2020-06-24  | 2         |
| 7            | 3           | 30          | 2020-06-25  | 2         |
| 9            | 3           | 30          | 2020-05-08  | 3         |
+--------------+-------------+-------------+-------------+-----------+

Result 表:

text
+--------------+------------+
| customer_id  | name       |  
+--------------+------------+
| 1            | Winston    |
+--------------+------------+ 

Winston 在2020年6月花费了$300(300 * 1), 在7月花费了$100(10 * 1 + 45 * 2).
Jonathan 在2020年6月花费了$600(300 * 2), 在7月花费了$20(2 * 10).
Moustafa 在2020年6月花费了$110 (10 * 2 + 45 * 2), 在7月花费了$0

sql
--简单题,在having判断之前先进行过滤是否效率会快一点?发现速度反而慢了.....
select
t1.customer_id,name 
from 
Customers t1 join Orders t2 on t1.customer_id = t2.customer_id
             join Product t3 on t2.product_id  = t3.product_id 
//where  month(order_date) = 6 or month(order_date) = 7
group by t1.customer_id 
having sum(if(left(order_date,7)="2020-06",price * quantity ,0 )) >= 100
       and    
       sum(if(left(order_date,7)="2020-07",price * quantity ,0 )) >= 100  

116.查找拥有有效邮箱的用户(正则匹配)

写一条 SQL 语句,查询拥有有效邮箱的用户
有效的邮箱包含符合下列条件的前缀名和域名:
前缀名是包含字母(大写或小写)、数字、下划线 '_'、句点 '.' 和/或横杠 '-' 的字符串。前缀名必须以字母开头。
域名是 '@leetcode.com' 

用户表: Users

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| name          | varchar |
| mail          | varchar | 
+---------------+---------+

user_id (用户 ID)是该表的主键。
这个表包含用户在某网站上注册的信息。有些邮箱是无效的。
 

写一条 SQL 语句,查询拥有有效邮箱的用户。

有效的邮箱包含符合下列条件的前缀名和域名:

前缀名是包含字母(大写或小写)、数字、下划线 '_'、句点 '.' 和/或横杠 '-' 的字符串。前缀名必须以字母开头。
域名是 '@leetcode.com' 。
按任意顺序返回结果表。

 

查询格式如下所示:

Users

text
+---------+-----------+-------------------------+
| user_id | name      | mail                    |
+---------+-----------+-------------------------+
| 1       | Winston   | winston@leetcode.com    |
| 2       | Jonathan  | jonathanisgreat         |
| 3       | Annabelle | bella-@leetcode.com     |
| 4       | Sally     | sally.come@leetcode.com |
| 5       | Marwan    | quarz#2020@leetcode.com |
| 6       | David     | david69@gmail.com       |
| 7       | Shapiro   | .shapo@leetcode.com     |
+---------+-----------+-------------------------+

结果表:

text
+---------+-----------+-------------------------+
| user_id | name      | mail                    |
+---------+-----------+-------------------------+
| 1       | Winston   | winston@leetcode.com    |
| 3       | Annabelle | bella-@leetcode.com     |
| 4       | Sally     | sally.come@leetcode.com |
+---------+-----------+-------------------------+

2 号用户的邮箱没有域名。
5 号用户的邮箱包含非法字符 #。
6 号用户的邮箱的域名不是 leetcode。
7 号用户的邮箱以句点(.)开头。

sql
--正则匹配,非常讨厌老忘记符号的含义....
select *
from users 
where mail regexp '^[a-zA-Z]+[a-zA-Z0-9_\\./\\-]*@leetcode\\.com$'

117.患某疾病的患者

写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。

患者信息表: Patients

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| patient_id   | int     |
| patient_name | varchar |
| conditions   | varchar |
+--------------+---------+

patient_id (患者 ID)是该表的主键。
'conditions' (疾病)包含 0 个或以上的疾病代码,以空格分隔。
这个表包含医院中患者的信息。
 

写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。

按任意顺序返回结果表。

查询结果格式如下示例所示:

 

Patients

text
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 1          | Daniel       | YFEV COUGH   |
| 2          | Alice        |              |
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 |
| 5          | Alain        | DIAB201      |
+------------+--------------+--------------+

结果表:

text
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 | 
+------------+--------------+--------------+

Bob 和 George 都患有代码以 DIAB1 开头的疾病

sql
--like用法,有一个通过不了限制一下....
SELECT 
    patient_id,
    patient_name,
    conditions
FROM Patients
WHERE conditions LIKE '%DIAB1%' AND conditions NOT LIKE 'SADIAB100'
sql
--正确的写法
select * from Patients where conditions  REGEXP '^DIAB1|\\sDIAB1'
sql
select * from patients where conditions like "DIAB1%" or conditions like "% DIAB1%"

118.最近的三笔订单

写一个 SQL 语句,找到每个用户的最近三笔订单。如果用户的订单少于 3 笔,则返回他的全部订单。

表:Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
+---------------+---------+

customer_id 是该表主键
该表包含消费者的信息
 

表:Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| cost          | int     |
+---------------+---------+

order_id 是该表主键
该表包含id为customer_id的消费者的订单信息
每一个消费者 每天一笔订单
 

写一个 SQL 语句,找到每个用户的最近三笔订单。如果用户的订单少于 3 笔,则返回他的全部订单。

返回的结果按照 customer_name 升序排列。如果排名有相同,则继续按照 customer_id 升序排列。如果排名还有相同,则继续按照 order_date 降序排列。

查询结果格式如下例所示:

Customers

text
+-------------+-----------+
| customer_id | name      |
+-------------+-----------+
| 1           | Winston   |
| 2           | Jonathan  |
| 3           | Annabelle |
| 4           | Marwan    |
| 5           | Khaled    |
+-------------+-----------+

Orders

text
+----------+------------+-------------+------+
| order_id | order_date | customer_id | cost |
+----------+------------+-------------+------+
| 1        | 2020-07-31 | 1           | 30   |
| 2        | 2020-07-30 | 2           | 40   |
| 3        | 2020-07-31 | 3           | 70   |
| 4        | 2020-07-29 | 4           | 100  |
| 5        | 2020-06-10 | 1           | 1010 |
| 6        | 2020-08-01 | 2           | 102  |
| 7        | 2020-08-01 | 3           | 111  |
| 8        | 2020-08-03 | 1           | 99   |
| 9        | 2020-08-07 | 2           | 32   |
| 10       | 2020-07-15 | 1           | 2    |
+----------+------------+-------------+------+

Result table:

text
+---------------+-------------+----------+------------+
| customer_name | customer_id | order_id | order_date |
+---------------+-------------+----------+------------+
| Annabelle     | 3           | 7        | 2020-08-01 |
| Annabelle     | 3           | 3        | 2020-07-31 |
| Jonathan      | 2           | 9        | 2020-08-07 |
| Jonathan      | 2           | 6        | 2020-08-01 |
| Jonathan      | 2           | 2        | 2020-07-30 |
| Marwan        | 4           | 4        | 2020-07-29 |
| Winston       | 1           | 8        | 2020-08-03 |
| Winston       | 1           | 1        | 2020-07-31 |
| Winston       | 1           | 10       | 2020-07-15 |
+---------------+-------------+----------+------------+

Winston 有 4 笔订单, 排除了 "2020-06-10" 的订单, 因为它是最老的订单。
Annabelle 只有 2 笔订单, 全部返回。
Jonathan 恰好有 3 笔订单。
Marwan 只有 1 笔订单。
结果表我们按照 customer_name 升序排列,customer_id 升序排列,order_date 降序排列。

sql
--简单题,窗口写法
--注意不能以name为分组,因为名字会重复...要以id.....
select 
name customer_name,
customer_id,
order_id,
order_date
from 
(
select
name,
t1.customer_id,
order_id,
order_date,
dense_rank() over(partition by t1.customer_id order by order_date desc ) as rn 
from Customers t1 join Orders t2 on t1.customer_id = t2.customer_id
) t1
where rn <=3
order by customer_name ,customer_id,order_date desc 
sql
SELECT c.name customer_name,o2.customer_id,o2.order_id,o2.order_date
FROM orders o1,orders o2,Customers c
WHERE o1.customer_id=o2.customer_id AND c.customer_id=o2.customer_id
GROUP BY c.name,o2.order_id,o2.customer_id,o2.order_date
HAVING SUM(o1.order_date>=o2.order_date)<=3
ORDER BY c.name,o2.customer_id,o2.order_date desc

119.产品名称格式修复(内容处理函数)

写一个 SQL 语句报告每个月的销售情况:
product_name 是小写字母且不包含前后空格
sale_date 格式为 ('YYYY-MM') 
total 是产品在本月销售的次数

表:Sales

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| sale_id      | int     |
| product_name | varchar |
| sale_date    | date    |
+--------------+---------+

sale_id 是该表主键
该表的每一行包含了产品的名称及其销售日期
因为在 2000 年该表是手工填写的,product_name 可能包含前后空格,而且包含大小写。

写一个 SQL 语句报告每个月的销售情况:

product_name 是小写字母且不包含前后空格
sale_date 格式为 ('YYYY-MM') 
total 是产品在本月销售的次数
返回结果以 product_name 升序 排列,如果有排名相同,再以 sale_date 升序 排列。

查询结果格式如下所示:

Sales 表:

text
+------------+------------------+--------------+
| sale_id    | product_name     | sale_date    |
+------------+------------------+--------------+
| 1          |      LCPHONE     | 2000-01-16   |
| 2          |    LCPhone       | 2000-01-17   |
| 3          |     LcPhOnE      | 2000-02-18   |
| 4          |      LCKeyCHAiN  | 2000-02-19   |
| 5          |   LCKeyChain     | 2000-02-28   |
| 6          | Matryoshka       | 2000-03-31   | 
+------------+------------------+--------------+

Result 表:

text
+--------------+--------------+----------+
| product_name | sale_date    | total    |
+--------------+--------------+----------+
| lcphone      | 2000-01      | 2        |
| lckeychain   | 2000-02      | 2        | 
| lcphone      | 2000-02      | 1        | 
| matryoshka   | 2000-03      | 1        | 
+--------------+--------------+----------+

1 月份,卖了 2 个 LcPhones,请注意产品名称是小写的,中间可能包含空格
2 月份,卖了 2 个 LCKeychains 和 1 个 LCPhone
3 月份,卖了 1 个 matryoshka

sql
--简单题,注意对数据的处理函数的学习,是我的薄弱点,
--replace 可用trim函数来代替
select
replace(lower(product_name),' ','') product_name ,left(sale_date,7) sale_date ,
count(1) total
from 
Sales
group by replace(lower(product_name),' ','') ,left(sale_date,7)
order by product_name,sale_date

120.每件商品的最新订单

写一个SQL 语句, 找到每件商品的最新订单(可能有多个)
返回的结果以 product_name 升序排列, 如果有排序相同, 再以 product_id 升序排列. 如果还有排序相同, 再以 order_id 升序排列

表: Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
+---------------+---------+

customer_id 是该表主键.
该表包含消费者的信息.
 

表: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| product_id    | int     |
+---------------+---------+

order_id 是该表主键.
该表包含消费者customer_id产生的订单.
不会有商品被相同的用户在一天内下单超过一次.
 

表: Products

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
| price         | int     |
+---------------+---------+

product_id 是该表主键.
该表包含所有商品的信息.
 

写一个SQL 语句, 找到每件商品的最新订单(可能有多个).

返回的结果以 product_name 升序排列, 如果有排序相同, 再以 product_id 升序排列. 如果还有排序相同, 再以 order_id 升序排列.

查询结果格式如下例所示:

Customers

text
+-------------+-----------+
| customer_id | name      |
+-------------+-----------+
| 1           | Winston   |
| 2           | Jonathan  |
| 3           | Annabelle |
| 4           | Marwan    |
| 5           | Khaled    |
+-------------+-----------+

Orders

text
+----------+------------+-------------+------------+
| order_id | order_date | customer_id | product_id |
+----------+------------+-------------+------------+
| 1        | 2020-07-31 | 1           | 1          |
| 2        | 2020-07-30 | 2           | 2          |
| 3        | 2020-08-29 | 3           | 3          |
| 4        | 2020-07-29 | 4           | 1          |
| 5        | 2020-06-10 | 1           | 2          |
| 6        | 2020-08-01 | 2           | 1          |
| 7        | 2020-08-01 | 3           | 1          |
| 8        | 2020-08-03 | 1           | 2          |
| 9        | 2020-08-07 | 2           | 3          |
| 10       | 2020-07-15 | 1           | 2          |
+----------+------------+-------------+------------+

Products

text
+------------+--------------+-------+
| product_id | product_name | price |
+------------+--------------+-------+
| 1          | keyboard     | 120   |
| 2          | mouse        | 80    |
| 3          | screen       | 600   |
| 4          | hard disk    | 450   |
+------------+--------------+-------+

Result

text
+--------------+------------+----------+------------+
| product_name | product_id | order_id | order_date |
+--------------+------------+----------+------------+
| keyboard     | 1          | 6        | 2020-08-01 |
| keyboard     | 1          | 7        | 2020-08-01 |
| mouse        | 2          | 8        | 2020-08-03 |
| screen       | 3          | 3        | 2020-08-29 |
+--------------+------------+----------+------------+

keyboard 的最新订单在2020-08-01, 在这天有两次下单
mouse 的最新订单在2020-08-03, 在这天只有一次下单
screen 的最新订单在2020-08-29, 在这天只有一次下单
hard disk 没有被下单, 我们不把它包含在结果表中

sql
--简单题,窗口写法
select
product_name,
product_id,
order_id,
order_date 
from 
(
select
product_name,
t3.product_id,
order_id,
order_date,
dense_rank() over(partition by t3.product_id order by order_date desc ) as rn 
from
Customers t1
join Orders t2 on t1.customer_id = t2.customer_id
join Products t3 on t2.product_id = t3.product_id
) t4
where rn =1
order by product_name,product_id,order_id
sql
SELECT
	p.product_name AS product_name,
	o2.product_id,
	o2.order_id,
	o2.order_date
FROM
	Orders o1,
	Orders o2,
	Customers c,
	Products p
WHERE
	o1.product_id = o2.product_id
AND o1.order_date >= o2.order_date
AND o2.customer_id = c.customer_id
AND o2.product_id = p.product_id
GROUP BY
	p.product_name,
	o2.product_id,
	o2.order_id,
	o2.order_date
HAVING
	COUNT(DISTINCT o1.order_date) = 1

练习题 12

121.银行账户概要

力扣银行 (LCB) 帮助程序员们完成虚拟支付。我们的银行在表 Transaction 中记录每条交易信息,我们要查询每个用户的当前余额,并检查他们是否已透支(当前额度小于 0)。
写一条 SQL 语句,查询:
user_id 用户 ID
user_name 用户名
credit 完成交易后的余额
credit_limit_breached 检查是否透支 ("Yes" 或 "No")

用户表: Users

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| user_name    | varchar |
| credit       | int     |
+--------------+---------+

user_id 是这个表的主键。
表中的每一列包含每一个用户当前的额度信息。
 

交易表:Transactions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| trans_id      | int     |
| paid_by       | int     |
| paid_to       | int     |
| amount        | int     |
| transacted_on | date    |
+---------------+---------+

trans_id 是这个表的主键。
表中的每一列包含银行的交易信息。
ID 为 paid_by 的用户给 ID 为 paid_to 的用户转账。
 

力扣银行 (LCB) 帮助程序员们完成虚拟支付。我们的银行在表 Transaction 中记录每条交易信息,我们要查询每个用户的当前余额,并检查他们是否已透支(当前额度小于 0)。

写一条 SQL 语句,查询:

user_id 用户 ID
user_name 用户名
credit 完成交易后的余额
credit_limit_breached 检查是否透支 ("Yes" 或 "No")
以任意顺序返回结果表。

 

查询格式见如下示例:

Users 表:

text
+------------+--------------+-------------+
| user_id    | user_name    | credit      |
+------------+--------------+-------------+
| 1          | Moustafa     | 100         |
| 2          | Jonathan     | 200         |
| 3          | Winston      | 10000       |
| 4          | Luis         | 800         | 
+------------+--------------+-------------+

Transactions 表:

text
+------------+------------+------------+----------+---------------+
| trans_id   | paid_by    | paid_to    | amount   | transacted_on |
+------------+------------+------------+----------+---------------+
| 1          | 1          | 3          | 400      | 2020-08-01    |
| 2          | 3          | 2          | 500      | 2020-08-02    |
| 3          | 2          | 1          | 200      | 2020-08-03    |
+------------+------------+------------+----------+---------------+

结果表:

text
+------------+------------+------------+-----------------------+
| user_id    | user_name  | credit     | credit_limit_breached |
+------------+------------+------------+-----------------------+
| 1          | Moustafa   | -100       | Yes                   | 
| 2          | Jonathan   | 500        | No                    |
| 3          | Winston    | 9900       | No                    |
| 4          | Luis       | 800        | No                    |
+------------+------------+------------+-----------------------+

Moustafa 在 "2020-08-01" 支付了 $400 并在 "2020-08-03" 收到了 $200 ,当前额度 (100 -400 +200) = -$100
Jonathan 在 "2020-08-02" 收到了 $500 并在 "2020-08-08" 支付了 $200 ,当前额度 (200 +500 -200) = $500
Winston 在 "2020-08-01" 收到了 $400 并在 "2020-08-03" 支付了 $500 ,当前额度 (10000 +400 -500) = $9900
Luis 未收到任何转账信息,额度 = $800

sql
--简单题,题意有点绕,实践一下join or的使用,也可以union all
select
t1.user_id,user_name,
max(credit) +
sum(
case when t1.user_id = t2.paid_by then - amount
     when t1.user_id = t2.paid_to then  amount
     else 0 end ) as credit,
if(max(credit) + sum(
case when t1.user_id = t2.paid_by then - amount
     when t1.user_id = t2.paid_to then  amount
     else 0 end) < 0,"Yes","No")  credit_limit_breached    
from
Users t1 
left join Transactions t2
on t1.user_id = t2.paid_by  or  t1.user_id = t2.paid_to 
group by t1.user_id,user_name  

122.按月统计订单数和顾客数

写一个查询语句来 按月 统计 金额大于 $20 的唯一 订单数 和唯一 顾客数 。

表:Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| invoice       | int     |
+---------------+---------+

order_id 是 Orders 表的主键。
这张表包含顾客(customer_id)所下订单的信息。
写一个查询语句来 按月 统计 金额大于 $20 的唯一 订单数 和唯一 顾客数 。

查询结果无排序要求。

查询结果格式如下面例子所示:

Orders

text
+----------+------------+-------------+------------+
| order_id | order_date | customer_id | invoice    |
+----------+------------+-------------+------------+
| 1        | 2020-09-15 | 1           | 30         |
| 2        | 2020-09-17 | 2           | 90         |
| 3        | 2020-10-06 | 3           | 20         |
| 4        | 2020-10-20 | 3           | 21         |
| 5        | 2020-11-10 | 1           | 10         |
| 6        | 2020-11-21 | 2           | 15         |
| 7        | 2020-12-01 | 4           | 55         |
| 8        | 2020-12-03 | 4           | 77         |
| 9        | 2021-01-07 | 3           | 31         |
| 10       | 2021-01-15 | 2           | 20         |
+----------+------------+-------------+------------+

Result 表:

text
+---------+-------------+----------------+
| month   | order_count | customer_count |
+---------+-------------+----------------+
| 2020-09 | 2           | 2              |
| 2020-10 | 1           | 1              |
| 2020-12 | 2           | 1              |
| 2021-01 | 1           | 1              |
+---------+-------------+----------------+

在 2020 年 09 月,有 2 份来自 2 位不同顾客的金额大于 $20 的订单。
在 2020 年 10 月,有 2 份来自 1 位顾客的订单,并且只有其中的 1 份订单金额大于 $20 。
在 2020 年 11 月,有 2 份来自 2 位不同顾客的订单,但由于金额都小于 $20 ,所以我们的查询结果中不包含这个月的数据。
在 2020 年 12 月,有 2 份来自 1 位顾客的订单,且 2 份订单金额都大于 $20 。
在 2021 年 01 月,有 2 份来自 2 位不同顾客的订单,但只有其中一份订单金额大于 $20

sql
--简单题,一开始我把where条件过滤,写到了select中来去重,发现语法不对?
select
left(order_date,7) month,
count(order_id) order_count,
count(distinct customer_id ) customer_count
from 
Orders
where invoice >20
group by left(order_date,7)

123.仓库经理

写一个 SQL 查询来报告, 每个仓库的存货量是多少立方英尺.

表: Warehouse

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| name         | varchar |
| product_id   | int     |
| units        | int     |
+--------------+---------+

(name, product_id) 是该表主键.
该表的行包含了每个仓库的所有商品信息.
 

表: Products

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
| Width         | int     |
| Length        | int     |
| Height        | int     |
+---------------+---------+

product_id 是该表主键.
该表的行包含了每件商品以英尺为单位的尺寸(宽度, 长度和高度)信息.
 

写一个 SQL 查询来报告, 每个仓库的存货量是多少立方英尺.

仓库名
存货量
返回结果没有顺序要求.

查询结果如下例所示.

 

Warehouse 表:

text
+------------+--------------+-------------+
| name       | product_id   | units       |
+------------+--------------+-------------+
| LCHouse1   | 1            | 1           |
| LCHouse1   | 2            | 10          |
| LCHouse1   | 3            | 5           |
| LCHouse2   | 1            | 2           |
| LCHouse2   | 2            | 2           |
| LCHouse3   | 4            | 1           |
+------------+--------------+-------------+

Products 表:

text
+------------+--------------+------------+----------+-----------+
| product_id | product_name | Width      | Length   | Height    |
+------------+--------------+------------+----------+-----------+
| 1          | LC-TV        | 5          | 50       | 40        |
| 2          | LC-KeyChain  | 5          | 5        | 5         |
| 3          | LC-Phone     | 2          | 10       | 10        |
| 4          | LC-T-Shirt   | 4          | 10       | 20        |
+------------+--------------+------------+----------+-----------+

Result 表:

text
+----------------+------------+
| WAREHOUSE_NAME | VOLUME     | 
+----------------+------------+
| LCHouse1       | 12250      | 
| LCHouse2       | 20250      |
| LCHouse3       | 800        |
+----------------+------------+

Id为1的商品(LC-TV)的存货量为 5x50x40 = 10000
Id为2的商品(LC-KeyChain)的存货量为 5x5x5 = 125
Id为3的商品(LC-Phone)的存货量为 2x10x10 = 200
Id为4的商品(LC-T-Shirt)的存货量为 4x10x20 = 800
仓库LCHouse1: 1个单位的LC-TV + 10个单位的LC-KeyChain + 5个单位的LC-Phone.
  总存货量为: 110000 + 10125 + 5200 = 12250 立方英尺
仓库LCHouse2: 2个单位的LC-TV + 2个单位的LC-KeyChain.
  总存货量为: 2
10000 + 2125 = 20250 立方英尺
仓库LCHouse3: 1个单位的LC-T-Shirt.
总存货量为: 1
800 = 800 立方英尺

sql
--简单题
select
name WAREHOUSE_NAME ,sum(units * Width *  Length * Height )  VOLUME 
from 
Warehouse t1
join Products t2 on t1.product_id  =t2.product_id
group by name

124.进店为进行交易过的顾客

有一些顾客可能光顾了购物中心但没有进行交易。请你编写一个 SQL 查询,来查找这些顾客的 ID ,以及他们只光顾不交易的次数。

表:Visits

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| visit_id    | int     |
| customer_id | int     |
+-------------+---------+

visit_id 是该表的主键。
该表包含有关光临过购物中心的顾客的信息。
 

表:Transactions

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| transaction_id | int     |
| visit_id       | int     |
| amount         | int     |
+----------------+---------+

transaction_id 是此表的主键。
此表包含 visit_id 期间进行的交易的信息。
有一些顾客可能光顾了购物中心但没有进行交易。请你编写一个 SQL 查询,来查找这些顾客的 ID ,以及他们只光顾不交易的次数。

返回以任何顺序排序的结果表。

查询结果格式如下例所示:

Visits

text
+----------+-------------+
| visit_id | customer_id |
+----------+-------------+
| 1        | 23          |
| 2        | 9           |
| 4        | 30          |
| 5        | 54          |
| 6        | 96          |
| 7        | 54          |
| 8        | 54          |
+----------+-------------+

Transactions

text
+----------------+----------+--------+
| transaction_id | visit_id | amount |
+----------------+----------+--------+
| 2              | 5        | 310    |
| 3              | 5        | 300    |
| 9              | 5        | 200    |
| 12             | 1        | 910    |
| 13             | 2        | 970    |
+----------------+----------+--------+

Result 表:

text
+-------------+----------------+
| customer_id | count_no_trans |
+-------------+----------------+
| 54          | 2              |
| 30          | 1              |
| 96          | 1              |
+-------------+----------------+

ID = 23 的顾客曾经逛过一次购物中心,并在 ID = 12 的访问期间进行了一笔交易。
ID = 9 的顾客曾经逛过一次购物中心,并在 ID = 13 的访问期间进行了一笔交易。
ID = 30 的顾客曾经去过购物中心,并且没有进行任何交易。
ID = 54 的顾客三度造访了购物中心。在 2 次访问中,他们没有进行任何交易,在 1 次访问中,他们进行了 3 次交易。
ID = 96 的顾客曾经去过购物中心,并且没有进行任何交易。
如我们所见,ID 为 30 和 96 的顾客一次没有进行任何交易就去了购物中心。顾客 54 也两次访问了购物中心并且没有进行任何交易

sql
--简单题
select
customer_id ,sum(if(amount is null,1,0)) count_no_trans
from
Visits t1
left join Transactions t2 on t1.visit_id = t2.visit_id
group by customer_id
having sum(if(amount is null,1,0)) >= 1
sql
--直接过滤
select v.customer_id, count(*) count_no_trans
from visits v left join transactions t on v.visit_id = t.visit_id
where t.visit_id  is null
group by v.customer_id
sql
--子查询
select customer_id 
    ,count(visit_id) as count_no_trans
from Visits
where visit_id not in (select visit_id from Transactions )
group by customer_id 

125.银行账户概要2

写一个 SQL, 报告余额高于 10000 的所有用户的名字和余额. 账户的余额等于包含该账户的所有交易的总和.

表: Users

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| account      | int     |
| name         | varchar |
+--------------+---------+

account 是该表的主键.
表中的每一行包含银行里中每一个用户的账号.
 

表: Transactions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| trans_id      | int     |
| account       | int     |
| amount        | int     |
| transacted_on | date    |
+---------------+---------+

trans_id 是该表主键.
该表的每一行包含了所有账户的交易改变情况.
如果用户收到了钱, 那么金额是正的; 如果用户转了钱, 那么金额是负的.
所有账户的起始余额为 0.
 

写一个 SQL,  报告余额高于 10000 的所有用户的名字和余额. 账户的余额等于包含该账户的所有交易的总和.

返回结果表单没有顺序要求.

查询结果格式如下例所示.

 

Users table:

text
+------------+--------------+
| account    | name         |
+------------+--------------+
| 900001     | Alice        |
| 900002     | Bob          |
| 900003     | Charlie      |
+------------+--------------+

Transactions table:

text
+------------+------------+------------+---------------+
| trans_id   | account    | amount     | transacted_on |
+------------+------------+------------+---------------+
| 1          | 900001     | 7000       |  2020-08-01   |
| 2          | 900001     | 7000       |  2020-09-01   |
| 3          | 900001     | -3000      |  2020-09-02   |
| 4          | 900002     | 1000       |  2020-09-12   |
| 5          | 900003     | 6000       |  2020-08-07   |
| 6          | 900003     | 6000       |  2020-09-07   |
| 7          | 900003     | -4000      |  2020-09-11   |
+------------+------------+------------+---------------+

Result table:

text
+------------+------------+
| name       | balance    |
+------------+------------+
| Alice      | 11000      |
+------------+------------+

Alice 的余额为(7000 + 7000 - 3000) = 11000.
Bob 的余额为1000.
Charlie 的余额为(6000 + 6000 - 4000) = 8000.

sql
--简单题
select
name  ,sum(amount) as balance
from 
Users t1 join  Transactions t2 on t1.account = t2.account
group by t1.account ,name  
having sum(amount) > 10000

126.每位顾客最常购买的商品

写一个 SQL 语句,找到每一个顾客最经常订购的商品。
结果表单应该有每一位至少下过一次单的顾客 customer_id , 他最经常订购的商品的 product_id 和 product_name。

表:Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
+---------------+---------+

customer_id 是该表主键
该表包含所有顾客的信息
 

表:Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| product_id    | int     |
+---------------+---------+

order_id 是该表主键
该表包含顾客 customer_id 的订单信息
没有顾客会在一天内订购相同的商品 多于一次
 

表:Products

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
| price         | int     |
+---------------+---------+

product_id 是该表主键
该表包含了所有商品的信息
 

写一个 SQL 语句,找到每一个顾客最经常订购的商品。

结果表单应该有每一位至少下过一次单的顾客 customer_id , 他最经常订购的商品的 product_id 和 product_name。

返回结果 没有顺序要求。

查询结果格式如下例所示:

Customers

text
+-------------+-------+
| customer_id | name  |
+-------------+-------+
| 1           | Alice |
| 2           | Bob   |
| 3           | Tom   |
| 4           | Jerry |
| 5           | John  |
+-------------+-------+

Orders

text
+----------+------------+-------------+------------+
| order_id | order_date | customer_id | product_id |
+----------+------------+-------------+------------+
| 1        | 2020-07-31 | 1           | 1          |
| 2        | 2020-07-30 | 2           | 2          |
| 3        | 2020-08-29 | 3           | 3          |
| 4        | 2020-07-29 | 4           | 1          |
| 5        | 2020-06-10 | 1           | 2          |
| 6        | 2020-08-01 | 2           | 1          |
| 7        | 2020-08-01 | 3           | 3          |
| 8        | 2020-08-03 | 1           | 2          |
| 9        | 2020-08-07 | 2           | 3          |
| 10       | 2020-07-15 | 1           | 2          |
+----------+------------+-------------+------------+

Products

text
+------------+--------------+-------+
| product_id | product_name | price |
+------------+--------------+-------+
| 1          | keyboard     | 120   |
| 2          | mouse        | 80    |
| 3          | screen       | 600   |
| 4          | hard disk    | 450   |
+------------+--------------+-------+

Result 表:

text
+-------------+------------+--------------+
| customer_id | product_id | product_name |
+-------------+------------+--------------+
| 1           | 2          | mouse        |
| 2           | 1          | keyboard     |
| 2           | 2          | mouse        |
| 2           | 3          | screen       |
| 3           | 3          | screen       |
| 4           | 1          | keyboard     |
+-------------+------------+--------------+

Alice (customer 1) 三次订购鼠标, 一次订购键盘, 所以鼠标是 Alice 最经常订购的商品.
Bob (customer 2) 一次订购键盘, 一次订购鼠标, 一次订购显示器, 所以这些都是 Bob 最经常订购的商品.
Tom (customer 3) 只两次订购显示器, 所以显示器是 Tom 最经常订购的商品.
Jerry (customer 4) 只一次订购键盘, 所以键盘是 Jerry 最经常订购的商品.
John (customer 5) 没有订购过商品, 所以我们并没有把 John 包含在结果表中.

sql
--简单题,窗口写法
select
customer_id,product_id,product_name 
from 
(
select
t1.customer_id,t3.product_id,product_name,
rank() over(partition by t1.customer_id order by count(1) desc) as rn 
from
Customers t1
join Orders t2 on t1.customer_id = t2.customer_id
join Products t3 on t2.product_id = t3.product_id
group by t1.customer_id,t3.product_id,product_name
) t2
where rn =1
sql
select customer_id, a.product_id, b.product_name from
    (select customer_id, product_id, count(product_id) ct from orders
    group by customer_id, product_id) a, products b
where a.product_id = b.product_id
and (customer_id,ct) in 
    (select customer_id, max(ct) from
        (select customer_id, count(product_id) ct from orders
        group by customer_id, product_id) tmp
    group by customer_id)

127.没有卖出的卖家

写一个SQL语句, 报告所有在2020年度没有任何卖出的卖家的名字.
返回结果按照 seller_name 升序排列.

表: Customer

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
+---------------+---------+

customer_id 是该表主键.
该表的每行包含网上商城的每一位顾客的信息.
 

表: Orders

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| sale_date     | date    |
| order_cost    | int     |
| customer_id   | int     |
| seller_id     | int     |
+---------------+---------+

order_id 是该表主键.
该表的每行包含网上商城的所有订单的信息.
sale_date 是顾客customer_id和卖家seller_id之间交易的日期.
 

表: Seller

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| seller_id     | int     |
| seller_name   | varchar |
+---------------+---------+

seller_id 是该表主键.
该表的每行包含每一位卖家的信息.
 

写一个SQL语句, 报告所有在2020年度没有任何卖出的卖家的名字.

返回结果按照 seller_name 升序排列.

查询结果格式如下例所示.

 

Customer 表:

text
+--------------+---------------+
| customer_id  | customer_name |
+--------------+---------------+
| 101          | Alice         |
| 102          | Bob           |
| 103          | Charlie       |
+--------------+---------------+

Orders 表:

text
+-------------+------------+--------------+-------------+-------------+
| order_id    | sale_date  | order_cost   | customer_id | seller_id   |
+-------------+------------+--------------+-------------+-------------+
| 1           | 2020-03-01 | 1500         | 101         | 1           |
| 2           | 2020-05-25 | 2400         | 102         | 2           |
| 3           | 2019-05-25 | 800          | 101         | 3           |
| 4           | 2020-09-13 | 1000         | 103         | 2           |
| 5           | 2019-02-11 | 700          | 101         | 2           |
+-------------+------------+--------------+-------------+-------------+

Seller 表:

text
+-------------+-------------+
| seller_id   | seller_name |
+-------------+-------------+
| 1           | Daniel      |
| 2           | Elizabeth   |
| 3           | Frank       |
+-------------+-------------+

Result 表:

text
+-------------+
| seller_name |
+-------------+
| Frank       |
+-------------+

Daniel在2020年3月卖出1次.
Elizabeth在2020年卖出2次, 在2019年卖出1次.
Frank在2019年卖出1次, 在2020年没有卖出.

sql
--简单题,考察where 和 on
select
seller_name
from 
Seller
where  seller_id not in 
(
select
seller_id 
from 
Orders
where left(sale_date,4) = "2020" 
)
order by seller_name
sql
select seller_name
from Seller s
left join Orders o on o.seller_id= s.seller_id
and sale_date like '2020%'
where o.seller_id is null
order by seller_name

128.找到遗失的id(recursive)

写一个 SQL 语句, 找到所有遗失的顾客id. 遗失的顾客id是指那些不在 Customers 表中, 值却处于 1 和表中最大 customer_id 之间的id.
注意: 最大的 customer_id 值不会超过 100.
返回结果按 ids 升序排列

表: Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
+---------------+---------+

customer_id 是该表主键.
该表第一行包含了顾客的名字和id.
 

写一个 SQL 语句, 找到所有遗失的顾客id. 遗失的顾客id是指那些不在 Customers 表中, 值却处于 1 和表中最大 customer_id 之间的id.

注意: 最大的 customer_id 值不会超过 100.

返回结果按 ids 升序排列

查询结果格式如下例所示.

 

Customers 表:

text
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1           | Alice         |
| 4           | Bob           |
| 5           | Charlie       |
+-------------+---------------+

Result 表:

text
+-----+
| ids |
+-----+
| 2   |
| 3   |
+-----+

表中最大的customer_id是5, 所以在范围[1,5]内, ID2和3从表中遗失.

https://dev.mysql.com/doc/refman/8.0/en/with.html#common-table-expressions-recursive
mysql8.0 循环写法

sql
with recursive x as (
select 1 as n 
union all 
select n + 1 from  x where n <100
)

select
n as ids  
from 
x
where  n <= (select max(customer_id) from customers) and n not in (select customer_id from customers)

129.三人国家代表队

有一个国家只有三所学校,这个国家的每一个学生只会注册一所学校。
这个国家正在参加一个竞赛,他们希望从这三所学校中各选出一个学生来组建一支三人的代表队。
例如:
member_A是从 SchoolA中选出的
member_B是从 SchoolB中选出的
member_C是从 SchoolC中选出的
被选中的学生具有不同的名字和ID(没有任何两个学生拥有相同的名字、没有任何两个学生拥有相同的ID)
使用上述条件,编写SQL查询语句来找到所有可能的三人国家代表队组合。

表: SchoolA

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| student_name  | varchar |
+---------------+---------+

student_id 是表的主键
表中的每一行包含了学校A中每一个学生的名字和ID
所有student_name在表中都是独一无二的
 

表: SchoolB

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| student_name  | varchar |
+---------------+---------+

student_id 是表的主键
表中的每一行包含了学校B中每一个学生的名字和ID
所有student_name在表中都是独一无二的
 

表: SchoolC

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| student_id    | int     |
| student_name  | varchar |
+---------------+---------+

student_id 是表的主键
表中的每一行包含了学校C中每一个学生的名字和ID
所有student_name在表中都是独一无二的
 

有一个国家只有三所学校,这个国家的每一个学生只会注册一所学校。

这个国家正在参加一个竞赛,他们希望从这三所学校中各选出一个学生来组建一支三人的代表队。

例如:

member_A是从 SchoolA中选出的
member_B是从 SchoolB中选出的
member_C是从 SchoolC中选出的
被选中的学生具有不同的名字和ID(没有任何两个学生拥有相同的名字、没有任何两个学生拥有相同的ID)
使用上述条件,编写SQL查询语句来找到所有可能的三人国家代表队组合。

查询结果接受任何顺序。

 

查询结果格式样例:

SchoolA table:

text
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1          | Alice        |
| 2          | Bob          |
+------------+--------------+

SchoolB table:

text
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 3          | Tom          |
+------------+--------------+

SchoolC table:

text
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 3          | Tom          |
| 2          | Jerry        |
| 10         | Alice        |
+------------+--------------+

预期结果:

text
+----------+----------+----------+
| member_A | member_B | member_C |
+----------+----------+----------+
| Alice    | Tom      | Jerry    |
| Bob      | Tom      | Alice    |
+----------+----------+----------+

让我们看看有哪些可能的组合:

  • (Alice, Tom, Tom) --> 不适用,因为member_B(Tom)和member_C(Tom)有相同的名字和ID
  • (Alice, Tom, Jerry) --> 可能的组合
  • (Alice, Tom, Alice) --> 不适用,因为member_A和member_C有相同的名字
  • (Bob, Tom, Tom) --> 不适用,因为member_B和member_C有相同的名字和ID
  • (Bob, Tom, Jerry) --> 不适用,因为member_A和member_C有相同的ID
  • (Bob, Tom, Alice) --> 可能的组合.
sql
--简单题,注意不要写错,检查了好久
select a.student_name as member_A,b.student_name as member_B,c.student_name as member_C 
from SchoolA a,SchoolB b,SchoolC c
where a.student_id <> b.student_id 
and a.student_id <> c.student_id 
and b.student_id <> c.student_id 
and a.student_name <> b.student_name 
and a.student_name <> c.student_name 
and b.student_name <> c.student_name

130.各赛事的用户注册率

写一条 SQL 语句,查询各赛事的用户注册百分率,保留两位小数。

用户表: Users

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| user_name   | varchar |
+-------------+---------+

user_id 是该表的主键。
该表中的每行包括用户 ID 和用户名。
 

注册表: Register

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| contest_id  | int     |
| user_id     | int     |
+-------------+---------+

(contest_id, user_id) 是该表的主键。
该表中的每行包含用户的 ID 和他们注册的赛事。
 

写一条 SQL 语句,查询各赛事的用户注册百分率,保留两位小数。

返回的结果表按 percentage 的降序排序,若相同则按 contest_id 的升序排序。

查询结果如下示例所示:

 

Users 表:

text
+---------+-----------+
| user_id | user_name |
+---------+-----------+
| 6       | Alice     |
| 2       | Bob       |
| 7       | Alex      |
+---------+-----------+

Register 表:

text
+------------+---------+
| contest_id | user_id |
+------------+---------+
| 215        | 6       |
| 209        | 2       |
| 208        | 2       |
| 210        | 6       |
| 208        | 6       |
| 209        | 7       |
| 209        | 6       |
| 215        | 7       |
| 208        | 7       |
| 210        | 2       |
| 207        | 2       |
| 210        | 7       |
+------------+---------+

结果表:

text
+------------+------------+
| contest_id | percentage |
+------------+------------+
| 208        | 100.0      |
| 209        | 100.0      |
| 210        | 100.0      |
| 215        | 66.67      |
| 207        | 33.33      |
+------------+------------+

所有用户都注册了 208、209 和 210 赛事,因此这些赛事的注册率为 100% ,我们按 contest_id 的降序排序加入结果表中。
Alice 和 Alex 注册了 215 赛事,注册率为 ((2/3) * 100) = 66.67%
Bob 注册了 207 赛事,注册率为 ((1/3) * 100) = 33.33%

sql
with x as (
select count(1) as t  from Users
)
select
contest_id,round(count(distinct user_id ) / (select x.t from x)  * 100,2) percentage
from 
Register 
group by  contest_id
order by percentage desc ,contest_id 

练习题 13

131.hopper公司查询1

编写SQL查询以报告2020年每个月的以下统计信息:
截至某月底,当前在Hopper公司工作的驾驶员数量(active_drivers)。
该月接受的乘车次数(accepted_rides)。
返回按month 升序排列的结果表,其中month 是月份的数字(一月是1,二月是2,依此类推)。

表: Drivers

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| driver_id   | int     |
| join_date   | date    |
+-------------+---------+

driver_id是该表的主键。
该表的每一行均包含驾驶员的ID以及他们加入Hopper公司的日期。
 

表: Rides

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| ride_id      | int     |
| user_id      | int     |
| requested_at | date    |
+--------------+---------+

ride_id是该表的主键。
该表的每一行均包含行程ID(ride_id),用户ID(user_id)以及该行程的日期(requested_at)。
该表中可能有一些不被接受的乘车请求。
 

表: AcceptedRides

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ride_id       | int     |
| driver_id     | int     |
| ride_distance | int     |
| ride_duration | int     |
+---------------+---------+

ride_id是该表的主键。
该表的每一行都包含已接受的行程信息。
表中的行程信息都在“Rides”表中存在。
 

编写SQL查询以报告2020年每个月的以下统计信息:

截至某月底,当前在Hopper公司工作的驾驶员数量(active_drivers)。
该月接受的乘车次数(accepted_rides)。
返回按month 升序排列的结果表,其中month 是月份的数字(一月是1,二月是2,依此类推)。

查询结果格式如下例所示。

表 Drivers:

text
+-----------+------------+
| driver_id | join_date  |
+-----------+------------+
| 10        | 2019-12-10 |
| 8         | 2020-1-13  |
| 5         | 2020-2-16  |
| 7         | 2020-3-8   |
| 4         | 2020-5-17  |
| 1         | 2020-10-24 |
| 6         | 2021-1-5   |
+-----------+------------+

表 Rides:

text
+---------+---------+--------------+
| ride_id | user_id | requested_at |
+---------+---------+--------------+
| 6       | 75      | 2019-12-9    |
| 1       | 54      | 2020-2-9     |
| 10      | 63      | 2020-3-4     |
| 19      | 39      | 2020-4-6     |
| 3       | 41      | 2020-6-3     |
| 13      | 52      | 2020-6-22    |
| 7       | 69      | 2020-7-16    |
| 17      | 70      | 2020-8-25    |
| 20      | 81      | 2020-11-2    |
| 5       | 57      | 2020-11-9    |
| 2       | 42      | 2020-12-9    |
| 11      | 68      | 2021-1-11    |
| 15      | 32      | 2021-1-17    |
| 12      | 11      | 2021-1-19    |
| 14      | 18      | 2021-1-27    |
+---------+---------+--------------+

表 AcceptedRides:

text
+---------+-----------+---------------+---------------+
| ride_id | driver_id | ride_distance | ride_duration |
+---------+-----------+---------------+---------------+
| 10      | 10        | 63            | 38            |
| 13      | 10        | 73            | 96            |
| 7       | 8         | 100           | 28            |
| 17      | 7         | 119           | 68            |
| 20      | 1         | 121           | 92            |
| 5       | 7         | 42            | 101           |
| 2       | 4         | 6             | 38            |
| 11      | 8         | 37            | 43            |
| 15      | 8         | 108           | 82            |
| 12      | 8         | 38            | 34            |
| 14      | 1         | 90            | 74            |
+---------+-----------+---------------+---------------+

结果表:

text
+-------+----------------+----------------+
| month | active_drivers | accepted_rides |
+-------+----------------+----------------+
| 1     | 2              | 0              |
| 2     | 3              | 0              |
| 3     | 4              | 1              |
| 4     | 4              | 0              |
| 5     | 5              | 0              |
| 6     | 5              | 1              |
| 7     | 5              | 1              |
| 8     | 5              | 1              |
| 9     | 5              | 0              |
| 10    | 6              | 0              |
| 11    | 6              | 2              |
| 12    | 6              | 1              |
+-------+----------------+----------------+

截至1月底->两个活跃的驾驶员(10,8),没有被接受的行程。
截至2月底->三个活跃的驾驶员(10,8,5),没有被接受的行程。
截至3月底->四个活跃的驾驶员(10,8,5,7),一个被接受的行程(10)。
截至4月底->四个活跃的驾驶员(10,8,5,7),没有被接受的行程。
截至5月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
截至6月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(13)。
截至7月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(7)。
截至8月底->五个活跃的驾驶员(10,8,5,7,4),一位接受的行程(17)。
截至9月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
截至10月底->六个活跃的驾驶员(10,8,5,7,4,1),没有被接受的行程。
截至11月底->六个活跃的驾驶员(10,8,5,7,4,1),两个被接受的行程(20,5)。
截至12月底->六个活跃的驾驶员(10,8,5,7,4,1),一个被接受的行程(2)。

sql
--有点难度,分析一下与我遇到的错误
//我一直没读懂第三列要求什么,直到看了答案,二:在求第三列的时候我要时间限制在<= 2020,事实上应该是=2020

第一步:循环求1-12
with recursive x as (
    select 1 as month
    union all 
    select month +1  from  x where month <=11
)

第二步:由题意我们要把2019年的驾驶员,归纳到1月份,事实上是要group 结合if就可以了,不需要union all 在求得每个月的新增驾驶员之后开窗获取sum() 累计的驾驶员数量
select
x.month,
ifnull(sum(driver_id_count) over(order by month),0) as  active_drivers,
from 
x left join 
(
select
if(year(join_date) < "2020",1,month(join_date))  month,
count(driver_id) driver_id_count
from 
Drivers
where  year(join_date) <= "2020"
group by if(year(join_date) < "2020",1,month(join_date))
) t1 on x.month = t1.month

第三步:和第二步一个思路,按照月份求取符合的id,注意去重,事实上,这里的题意不怎么明确,join  on 的条件是month 

综上有:下面的SQL

with recursive x as (
    select 1 as month
    union all 
    select month +1  from  x where month <=11

)
select
x.month,
ifnull(sum(driver_id_count) over(order by month),0) as  active_drivers,
ifnull(accepted_rides,0) accepted_rides
from 
x left join 
(
select
if(year(join_date) < "2020",1,month(join_date))  month,
count(driver_id) driver_id_count
from 
Drivers
where  year(join_date) <= "2020"
group by if(year(join_date) < "2020",1,month(join_date))
) t1 on x.month = t1.month
left join 
(
select
if(year(requested_at) < "2020",1,month(requested_at))  month, 
count(distinct ride_id) accepted_rides
from 
Rides
where year(requested_at) = "2020" and ride_id in (select ride_id  from AcceptedRides)
group by if(year(requested_at) < "2020",1,month(requested_at)) 
) t2
on x.month = t2.month
order by month

132.hopper公司查询2

编写一个SQL查询,报告2020年每个月工作驱动程序的百分比(working_percentage),注意,如果一个月内可用驱动程序的数量为零,我们认为working_percentage为0,返回按月升序排序的结果表

sql
Table: Drivers

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| driver_id   | int     |
| join_date   | date    |
+-------------+---------+
driver_id is the primary key for this table.
Each row of this table contains the driver's ID and the date they joined the Hopper company.
 

Table: Rides

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| ride_id      | int     |
| user_id      | int     |
| requested_at | date    |
+--------------+---------+
ride_id is the primary key for this table.
Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
There may be some ride requests in this table that were not accepted.
 

Table: AcceptedRides

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ride_id       | int     |
| driver_id     | int     |
| ride_distance | int     |
| ride_duration | int     |
+---------------+---------+
ride_id is the primary key for this table.
Each row of this table contains some information about an accepted ride.
It is guaranteed that each accepted ride exists in the Rides table.
 

Write an SQL query to report the percentage of working drivers (working_percentage) for each month of 2020 where:

Note that if the number of available drivers during a month is zero, we consider the working_percentage to be 0.

Return the result table ordered by month in ascending order, where month is the month's number (January is 1, February is 2, etc.). Round working_percentage to the nearest 2 decimal places.

The query result format is in the following example.

 

Drivers table:
+-----------+------------+
| driver_id | join_date  |
+-----------+------------+
| 10        | 2019-12-10 |
| 8         | 2020-1-13  |
| 5         | 2020-2-16  |
| 7         | 2020-3-8   |
| 4         | 2020-5-17  |
| 1         | 2020-10-24 |
| 6         | 2021-1-5   |
+-----------+------------+

Rides table:
+---------+---------+--------------+
| ride_id | user_id | requested_at |
+---------+---------+--------------+
| 6       | 75      | 2019-12-9    |
| 1       | 54      | 2020-2-9     |
| 10      | 63      | 2020-3-4     |
| 19      | 39      | 2020-4-6     |
| 3       | 41      | 2020-6-3     |
| 13      | 52      | 2020-6-22    |
| 7       | 69      | 2020-7-16    |
| 17      | 70      | 2020-8-25    |
| 20      | 81      | 2020-11-2    |
| 5       | 57      | 2020-11-9    |
| 2       | 42      | 2020-12-9    |
| 11      | 68      | 2021-1-11    |
| 15      | 32      | 2021-1-17    |
| 12      | 11      | 2021-1-19    |
| 14      | 18      | 2021-1-27    |
+---------+---------+--------------+

AcceptedRides table:
+---------+-----------+---------------+---------------+
| ride_id | driver_id | ride_distance | ride_duration |
+---------+-----------+---------------+---------------+
| 10      | 10        | 63            | 38            |
| 13      | 10        | 73            | 96            |
| 7       | 8         | 100           | 28            |
| 17      | 7         | 119           | 68            |
| 20      | 1         | 121           | 92            |
| 5       | 7         | 42            | 101           |
| 2       | 4         | 6             | 38            |
| 11      | 8         | 37            | 43            |
| 15      | 8         | 108           | 82            |
| 12      | 8         | 38            | 34            |
| 14      | 1         | 90            | 74            |
+---------+-----------+---------------+---------------+

Result table:
+-------+--------------------+
| month | working_percentage |
+-------+--------------------+
| 1     | 0.00               |
| 2     | 0.00               |
| 3     | 25.00              |
| 4     | 0.00               |
| 5     | 0.00               |
| 6     | 20.00              |
| 7     | 20.00              |
| 8     | 20.00              |
| 9     | 0.00               |
| 10    | 0.00               |
| 11    | 33.33              |
| 12    | 16.67              |
+-------+--------------------+

By the end of January --> two active drivers (10, 8) and no accepted rides. The percentage is 0%.
By the end of February --> three active drivers (10, 8, 5) and no accepted rides. The percentage is 0%.
By the end of March --> four active drivers (10, 8, 5, 7) and one accepted ride by driver (10). The percentage is (1 / 4) * 100 = 25%.
By the end of April --> four active drivers (10, 8, 5, 7) and no accepted rides. The percentage is 0%.
By the end of May --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
By the end of June --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (10). The percentage is (1 / 5) * 100 = 20%.
By the end of July --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (8). The percentage is (1 / 5) * 100 = 20%.
By the end of August --> five active drivers (10, 8, 5, 7, 4) and one accepted ride by driver (7). The percentage is (1 / 5) * 100 = 20%.
By the end of Septemeber --> five active drivers (10, 8, 5, 7, 4) and no accepted rides. The percentage is 0%.
By the end of October --> six active drivers (10, 8, 5, 7, 4, 1) and no accepted rides. The percentage is 0%.
By the end of November --> six active drivers (10, 8, 5, 7, 4, 1) and two accepted rides by two different drivers (1, 7). The percentage is (2 / 6) * 100 = 33.33%.
By the end of December --> six active drivers (10, 8, 5, 7, 4, 1) and one accepted ride by driver (4). The percentage is (1 / 6) * 100 = 16.67%.
sql
--没有翻译难受,事实上就是第一题,区别就是在AcceptedRides表获取每个月的驾驶员
WITH
    recursive full_month AS 
    (
    SELECT 1 AS month
    union
    SELECT month+1 AS month FROM full_month WHERE month <= 11
    ),

    month_drivers AS
    (SELECT count(driver_id) AS nums,if(year(join_date)<'2020',1,month(join_date)) month
    FROM Drivers WHERE year(join_date) <= '2020' GROUP BY month),

    month_active AS
    (SELECT month(requested_at) month, count(distinct driver_id) AS counts
    FROM Rides r left join AcceptedRides a on r.ride_id = a.ride_id
    WHERE year(requested_at) = '2020'
    GROUP BY month)

SELECT month,
    if(driver_num=0,0,round(actice_num/driver_num*100,2)) AS working_percentage 
FROM
    (
    SELECT 
        t1.month, 
        ifnull(sum(t2.nums) over(order by month),0) AS driver_num,
        ifnull(t3.counts,0) AS actice_num
    FROM
        full_month t1 left join month_drivers t2 on t1.month = t2.month left join month_active t3 on t3.month = t1.month
    ) AS t
GROUP BY month
ORDER BY month

133.hopper公司查询3

编写一个SQL查询来计算从2020年1月- 3月到2020年10月- 12月的每个3个月窗口的平均ride_distance和平均ride_duration。将average ride_distance和average ride_duration四舍五入到小数点后两位。

sql
Table: Drivers

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| driver_id   | int     |
| join_date   | date    |
+-------------+---------+
driver_id is the primary key for this table.
Each row of this table contains the driver's ID and the date they joined the Hopper company.
 

Table: Rides

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| ride_id      | int     |
| user_id      | int     |
| requested_at | date    |
+--------------+---------+
ride_id is the primary key for this table.
Each row of this table contains the ID of a ride, the user's ID that requested it, and the day they requested it.
There may be some ride requests in this table that were not accepted.
 

Table: AcceptedRides

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ride_id       | int     |
| driver_id     | int     |
| ride_distance | int     |
| ride_duration | int     |
+---------------+---------+
ride_id is the primary key for this table.
Each row of this table contains some information about an accepted ride.
It is guaranteed that each accepted ride exists in the Rides table.
 

Write an SQL query to compute the average_ride_distance and average_ride_duration of every 3-month window starting from January - March 2020 to October - December 2020. Round average_ride_distance and average_ride_duration to the nearest two decimal places.

The average_ride_distance is calculated by summing up the total ride_distance values from the three months and dividing it by 3. The average_ride_duration is calculated in a similar way.

Return the result table ordered by month in ascending order, where month is the starting month's number (January is 1, February is 2, etc.).

The query result format is in the following example.

 

Drivers table:
+-----------+------------+
| driver_id | join_date  |
+-----------+------------+
| 10        | 2019-12-10 |
| 8         | 2020-1-13  |
| 5         | 2020-2-16  |
| 7         | 2020-3-8   |
| 4         | 2020-5-17  |
| 1         | 2020-10-24 |
| 6         | 2021-1-5   |
+-----------+------------+

Rides table:
+---------+---------+--------------+
| ride_id | user_id | requested_at |
+---------+---------+--------------+
| 6       | 75      | 2019-12-9    |
| 1       | 54      | 2020-2-9     |
| 10      | 63      | 2020-3-4     |
| 19      | 39      | 2020-4-6     |
| 3       | 41      | 2020-6-3     |
| 13      | 52      | 2020-6-22    |
| 7       | 69      | 2020-7-16    |
| 17      | 70      | 2020-8-25    |
| 20      | 81      | 2020-11-2    |
| 5       | 57      | 2020-11-9    |
| 2       | 42      | 2020-12-9    |
| 11      | 68      | 2021-1-11    |
| 15      | 32      | 2021-1-17    |
| 12      | 11      | 2021-1-19    |
| 14      | 18      | 2021-1-27    |
+---------+---------+--------------+

AcceptedRides table:
+---------+-----------+---------------+---------------+
| ride_id | driver_id | ride_distance | ride_duration |
+---------+-----------+---------------+---------------+
| 10      | 10        | 63            | 38            |
| 13      | 10        | 73            | 96            |
| 7       | 8         | 100           | 28            |
| 17      | 7         | 119           | 68            |
| 20      | 1         | 121           | 92            |
| 5       | 7         | 42            | 101           |
| 2       | 4         | 6             | 38            |
| 11      | 8         | 37            | 43            |
| 15      | 8         | 108           | 82            |
| 12      | 8         | 38            | 34            |
| 14      | 1         | 90            | 74            |
+---------+-----------+---------------+---------------+

Result table:
+-------+-----------------------+-----------------------+
| month | average_ride_distance | average_ride_duration |
+-------+-----------------------+-----------------------+
| 1     | 21.00                 | 12.67                 |
| 2     | 21.00                 | 12.67                 |
| 3     | 21.00                 | 12.67                 |
| 4     | 24.33                 | 32.00                 |
| 5     | 57.67                 | 41.33                 |
| 6     | 97.33                 | 64.00                 |
| 7     | 73.00                 | 32.00                 |
| 8     | 39.67                 | 22.67                 |
| 9     | 54.33                 | 64.33                 |
| 10    | 56.33                 | 77.00                 |
+-------+-----------------------+-----------------------+

By the end of January --> average_ride_distance = (0+0+63)/3=21, average_ride_duration = (0+0+38)/3=12.67
By the end of February --> average_ride_distance = (0+63+0)/3=21, average_ride_duration = (0+38+0)/3=12.67
By the end of March --> average_ride_distance = (63+0+0)/3=21, average_ride_duration = (38+0+0)/3=12.67
By the end of April --> average_ride_distance = (0+0+73)/3=24.33, average_ride_duration = (0+0+96)/3=32.00
By the end of May --> average_ride_distance = (0+73+100)/3=57.67, average_ride_duration = (0+96+28)/3=41.33
By the end of June --> average_ride_distance = (73+100+119)/3=97.33, average_ride_duration = (96+28+68)/3=64.00
By the end of July --> average_ride_distance = (100+119+0)/3=73.00, average_ride_duration = (28+68+0)/3=32.00
By the end of August --> average_ride_distance = (119+0+0)/3=39.67, average_ride_duration = (68+0+0)/3=22.67
By the end of Septemeber --> average_ride_distance = (0+0+163)/3=54.33, average_ride_duration = (0+0+193)/3=64.33
By the end of October --> average_ride_distance = (0+163+6)/3=56.33, average_ride_duration = (0+193+38)/3=77.00
sql
WITH RECURSIVE cte (month) AS
(
  SELECT 1
  UNION ALL
  SELECT month + 1 FROM cte WHERE month < 10
)

SELECT
    cte.month,
    ROUND(SUM(IFNULL(ride_distance,0))/3,2) average_ride_distance,
    ROUND(SUM(IFNULL(ride_duration,0))/3,2) average_ride_duration
FROM 
    cte
LEFT JOIN
    Rides r
ON MONTH(r.requested_at) BETWEEN cte.month AND cte.month + 2 AND r.requested_at BETWEEN '2020-01-01' AND '2020-12-31'
LEFT JOIN
    AcceptedRides a
ON r.ride_id = a.ride_id
GROUP BY
    cte.month
ORDER BY
    month
sql
WITH RECURSIVE cte(n) AS (
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM cte WHERE n < 12
)

SELECT month, average_ride_distance, average_ride_duration
FROM (
SELECT cte.n AS `month`,
       ROUND(AVG(IFNULL(ride_distance, 0)) OVER(ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING), 2) AS average_ride_distance,
       ROUND(AVG(IFNULL(ride_duration, 0)) OVER(ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING), 2) AS average_ride_duration
FROM cte 
LEFT JOIN (
SELECT MONTH(requested_at) AS `month`,
       SUM(ride_distance) AS ride_distance,
       SUM(ride_duration) AS ride_duration
FROM AcceptedRides A 
JOIN Rides R USING(ride_id)
WHERE YEAR(requested_at) = 2020
GROUP BY MONTH(requested_at)) T ON cte.n = T.month) T2 
WHERE month <= 10

134.每台机器的平均运行时间

现在有一个工厂网站由几台机器运行,每台机器上运行着相同数量的进程. 请写出一条SQL计算每台机器各自完成一个进程任务的平均耗时.
完成一个进程任务的时间指进程的'end' 时间戳 减去 'start' 时间戳. 平均耗时通过计算每台机器上所有进程任务的总耗费时间除以机器上的总进程数量获得.
结果表必须包含machine_id(机器ID) 和对应的 average time(平均耗时) 别名 processing_time, 且四舍五入保留3位小数.

表: Activity

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| machine_id     | int     |
| process_id     | int     |
| activity_type  | enum    |
| timestamp      | float   |
+----------------+---------+

该表展示了一家工厂网站的用户活动.
(machine_id, process_id, activity_type) 是当前表的主键.
machine_id 是一台机器的ID号.
process_id 是运行在各机器上的进程ID号.
activity_type 是枚举类型 ('start', 'end').
timestamp 是浮点类型,代表当前时间(以秒为单位).
'start' 代表该进程在这台机器上的开始运行时间戳 , 'end' 代表该进程在这台机器上的终止运行时间戳.
同一台机器,同一个进程都有一对开始时间戳和结束时间戳,而且开始时间戳永远在结束时间戳前面.
 

现在有一个工厂网站由几台机器运行,每台机器上运行着相同数量的进程. 请写出一条SQL计算每台机器各自完成一个进程任务的平均耗时.

完成一个进程任务的时间指进程的'end' 时间戳 减去 'start' 时间戳. 平均耗时通过计算每台机器上所有进程任务的总耗费时间除以机器上的总进程数量获得.

结果表必须包含machine_id(机器ID) 和对应的 average time(平均耗时) 别名 processing_time, 且四舍五入保留3位小数.

具体参考例子如下:

 

Activity table:

text
+------------+------------+---------------+-----------+
| machine_id | process_id | activity_type | timestamp |
+------------+------------+---------------+-----------+
| 0          | 0          | start         | 0.712     |
| 0          | 0          | end           | 1.520     |
| 0          | 1          | start         | 3.140     |
| 0          | 1          | end           | 4.120     |
| 1          | 0          | start         | 0.550     |
| 1          | 0          | end           | 1.550     |
| 1          | 1          | start         | 0.430     |
| 1          | 1          | end           | 1.420     |
| 2          | 0          | start         | 4.100     |
| 2          | 0          | end           | 4.512     |
| 2          | 1          | start         | 2.500     |
| 2          | 1          | end           | 5.000     |
+------------+------------+---------------+-----------+

Result table:

text
+------------+-----------------+
| machine_id | processing_time |
+------------+-----------------+
| 0          | 0.894           |
| 1          | 0.995           |
| 2          | 1.456           |
+------------+-----------------+

一共有3台机器,每台机器运行着两个进程.
机器 0 的平均耗时: ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
机器 1 的平均耗时: ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
机器 2 的平均耗时: ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456

sql
--简单题,终于是中文的了.....
select
machine_id,
round(sum(if(activity_type = "end",timestamp,-timestamp)) / count(distinct process_id ) ,3) processing_time
from 
Activity
group by 
machine_id

135.修复表中的名字

编写一个 SQL 查询来修复名字,使得只有第一个字符是大写的,其余都是小写的。

表:

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+
user_id 是该表的主键。
该表包含用户的 ID 和名字。名字仅由小写和大写字符组成。
 

编写一个 SQL 查询来修复名字,使得只有第一个字符是大写的,其余都是小写的。

返回按 user_id 排序的结果表。

查询结果格式示例如下:

Users table:
+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | aLice |
| 2       | bOB   |
+---------+-------+

Result table:
+---------+-------+
| user_id | name  |
+---------+-------+
| 1       | Alice |
| 2       | Bob   |
+---------+-------+
sql
--简单题
select
user_id,
concat(upper(left(name,1)),lower(substr(name,2))) as name
from 
Users
order by 
user_id
sql
--length函数
select user_id,
concat(upper(substr(name,1,1)),lower(substr(name,2,length(name)-1))) as name

from users
order by user_id

136.发票中的产品金额

要求写一个SQL查询,返回全部发票中每个产品的产品名称、总应缴款项、总已支付金额、总已取消金额、总已退款金额
查询结果按 product_name排序

Product 表:

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| name        | varchar |
+-------------+---------+

product_id 是这张表的主键
表中含有产品 id 、产品名称。产品名称都是小写的英文字母,产品名称都是唯一的
 

Invoice 表:

text
+-------------+------+
| Column Name | Type |
+-------------+------+
| invoice_id  | int  |
| product_id  | int  |
| rest        | int  |
| paid        | int  |
| canceled    | int  |
| refunded    | int  |
+-------------+------+

invoice_id 发票 id ,是这张表的主键
product_id 产品 id
rest 应缴款项
paid 已支付金额
canceled 已取消金额
refunded 已退款金额
 

要求写一个SQL查询,返回全部发票中每个产品的产品名称、总应缴款项、总已支付金额、总已取消金额、总已退款金额

查询结果按 product_name排序

示例:

Product 表:

text
+------------+-------+
| product_id | name  |
+------------+-------+
| 0          | ham   |
| 1          | bacon |
+------------+-------+

Invoice table:

text
+------------+------------+------+------+----------+----------+
| invoice_id | product_id | rest | paid | canceled | refunded |
+------------+------------+------+------+----------+----------+
| 23         | 0          | 2    | 0    | 5        | 0        |
| 12         | 0          | 0    | 4    | 0        | 3        |
| 1          | 1          | 1    | 1    | 0        | 1        |
| 2          | 1          | 1    | 0    | 1        | 1        |
| 3          | 1          | 0    | 1    | 1        | 1        |
| 4          | 1          | 1    | 1    | 1        | 0        |
+------------+------------+------+------+----------+----------+

Result 表:

text
+-------+------+------+----------+----------+
| name  | rest | paid | canceled | refunded |
+-------+------+------+----------+----------+
| bacon | 3    | 3    | 3        | 3        |
| ham   | 2    | 4    | 5        | 3        |
+-------+------+------+----------+----------+
  • bacon 的总应缴款项为 1 + 1 + 0 + 1 = 3
  • bacon 的总已支付金额为 1 + 0 + 1 + 1 = 3
  • bacon 的总已取消金额为 0 + 1 + 1 + 1 = 3
  • bacon 的总已退款金额为 1 + 1 + 1 + 0 = 3
  • ham 的总应缴款项为 2 + 0 = 2
  • ham 的总已支付金额为 0 + 4 = 4
  • ham 的总已取消金额为 5 + 0 = 5
  • ham 的总已退款金额为 0 + 3 = 3
sql
select
name,
sum( rest)   rest ,
sum(paid) paid,
sum(canceled) canceled,
sum(refunded ) refunded 
from 
Product t1  join Invoice t2 on t1. product_id =t2. product_id
group by t1. product_id ,name 
order by name 

137.无效的推文

写一条 SQL 语句,查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。

表:Tweets

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| tweet_id       | int     |
| content        | varchar |
+----------------+---------+

tweet_id 是这个表的主键。
这个表包含某社交媒体 App 中所有的推文。
 

写一条 SQL 语句,查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。

以任意顺序返回结果表。

查询结果格式如下示例所示:

 

Tweets 表:

text
+----------+----------------------------------+
| tweet_id | content                          |
+----------+----------------------------------+
| 1        | Vote for Biden                   |
| 2        | Let us make America great again! |
+----------+----------------------------------+

结果表:

text
+----------+
| tweet_id |
+----------+
| 2        |
+----------+

推文 1 的长度 length = 14。该推文是有效的。
推文 2 的长度 length = 32。该推文是无效的。

sql
--简单题
select
tweet_id 
from
Tweets
where length(trim(content )) >15

1、char_length(str)
(1)计算单位:字符
(2)不管汉字还是数字或者是字母都算是一个字符
2、length(str)
(1)计算单位:字节
(2)utf8编码:一个汉字三个字节,一个数字或字母一个字节。
(3)gbk编码:一个汉字两个字节,一个数字或字母一个字节。

sql
//注意一下上面的区别

138.每天的领导和合伙人

写一条 SQL 语句,使得对于每一个 date_id 和 make_name,返回不同的 lead_id 以及不同的 partner_id 的数量。

表:DailySales

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| date_id     | date    |
| make_name   | varchar |
| lead_id     | int     |
| partner_id  | int     |
+-------------+---------+

该表没有主键。
该表包含日期、产品的名称,以及售给的领导和合伙人的编号。
名称只包含小写英文字母。
 

写一条 SQL 语句,使得对于每一个 date_id 和 make_name,返回不同的 lead_id 以及不同的 partner_id 的数量。

按任意顺序返回结果表。

查询结果格式如下示例所示:

 

DailySales 表:

text
+-----------+-----------+---------+------------+
| date_id   | make_name | lead_id | partner_id |
+-----------+-----------+---------+------------+
| 2020-12-8 | toyota    | 0       | 1          |
| 2020-12-8 | toyota    | 1       | 0          |
| 2020-12-8 | toyota    | 1       | 2          |
| 2020-12-7 | toyota    | 0       | 2          |
| 2020-12-7 | toyota    | 0       | 1          |
| 2020-12-8 | honda     | 1       | 2          |
| 2020-12-8 | honda     | 2       | 1          |
| 2020-12-7 | honda     | 0       | 1          |
| 2020-12-7 | honda     | 1       | 2          |
| 2020-12-7 | honda     | 2       | 1          |
+-----------+-----------+---------+------------+

结果表:

text
+-----------+-----------+--------------+-----------------+
| date_id   | make_name | unique_leads | unique_partners |
+-----------+-----------+--------------+-----------------+
| 2020-12-8 | toyota    | 2            | 3               |
| 2020-12-7 | toyota    | 1            | 2               |
| 2020-12-8 | honda     | 2            | 2               |
| 2020-12-7 | honda     | 3            | 2               |
+-----------+-----------+--------------+-----------------+

在 2020-12-8,丰田(toyota)有领导者 = [0, 1] 和合伙人 = [0, 1, 2] ,同时本田(honda)有领导者 = [1, 2] 和合伙人 = [1, 2]。
在 2020-12-7,丰田(toyota)有领导者 = [0] 和合伙人 = [1, 2] ,同时本田(honda)有领导者 = [0, 1, 2] 和合伙人 = [1, 2]。

sql
--简单题
select
date_id,make_name,
count(distinct lead_id) unique_leads ,
count(distinct partner_id )  unique_partners
from 
DailySales
group by  date_id , make_name

139.两人之间的通话次数

编写 SQL 语句,查询每一对用户 (person1, person2) 之间的通话次数和通话总时长,其中 person1 < person2 。

表: Calls

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| from_id     | int     |
| to_id       | int     |
| duration    | int     |
+-------------+---------+

该表没有主键,可能存在重复项。
该表包含 from_id 与 to_id 间的一次电话的时长。
from_id != to_id
 

编写 SQL 语句,查询每一对用户 (person1, person2) 之间的通话次数和通话总时长,其中 person1 < person2 。

以任意顺序返回结果表。

查询结果格式如下示例所示:

 

Calls 表:

text
+---------+-------+----------+
| from_id | to_id | duration |
+---------+-------+----------+
| 1       | 2     | 59       |
| 2       | 1     | 11       |
| 1       | 3     | 20       |
| 3       | 4     | 100      |
| 3       | 4     | 200      |
| 3       | 4     | 200      |
| 4       | 3     | 499      |
+---------+-------+----------+

结果表:

text
+---------+---------+------------+----------------+
| person1 | person2 | call_count | total_duration |
+---------+---------+------------+----------------+
| 1       | 2       | 2          | 70             |
| 1       | 3       | 1          | 20             |
| 3       | 4       | 4          | 999            |
+---------+---------+------------+----------------+

用户 1 和 2 打过 2 次电话,总时长为 70 (59 + 11)
用户 1 和 3 打过 1 次电话,总时长为 20
用户 3 和 4 打过 4 次电话,总时长为 999 (100 + 200 + 200 + 499)

sql
--简单题
select
person1,person2,
count(1) as  call_count,
sum(duration) total_duration
from 
(
select
if(from_id<to_id,from_id,to_id)  person1,
if(from_id>to_id,from_id,to_id)  person2,
duration
from
Calls 
) t1
group by 1,2

140.访问日期之间最大的空档期

假设今天的日期是 '2021-1-1' 。
编写 SQL 语句,对于每个 user_id ,求出每次访问及其下一个访问(若该次访问是最后一次,则为今天)之间最大的空档期天数 window 。
返回结果表,按用户编号 user_id 排序

表: UserVisits

text
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| visit_date  | date |
+-------------+------+

该表没有主键。
该表包含用户访问某特定零售商的日期日志。
 

假设今天的日期是 '2021-1-1' 。

编写 SQL 语句,对于每个 user_id ,求出每次访问及其下一个访问(若该次访问是最后一次,则为今天)之间最大的空档期天数 window 。

返回结果表,按用户编号 user_id 排序。

查询格式如下示例所示:

 

UserVisits 表:

text
+---------+------------+
| user_id | visit_date |
+---------+------------+
| 1       | 2020-11-28 |
| 1       | 2020-10-20 |
| 1       | 2020-12-3  |
| 2       | 2020-10-5  |
| 2       | 2020-12-9  |
| 3       | 2020-11-11 |
+---------+------------+

结果表:

text
+---------+---------------+
| user_id | biggest_window|
+---------+---------------+
| 1       | 39            |
| 2       | 65            |
| 3       | 51            |
+---------+---------------+

对于第一个用户,问题中的空档期在以下日期之间:
- 2020-10-20 至 2020-11-28 ,共计 39 天。
- 2020-11-28 至 2020-12-3 ,共计 5 天。
- 2020-12-3 至 2021-1-1 ,共计 29 天。
由此得出,最大的空档期为 39 天。
对于第二个用户,问题中的空档期在以下日期之间:
- 2020-10-5 至 2020-12-9 ,共计 65 天。
- 2020-12-9 至 2021-1-1 ,共计 23 天。
由此得出,最大的空档期为 65 天。
对于第三个用户,问题中的唯一空档期在 2020-11-11 至 2021-1-1 之间,共计 51 天。

sql
--简单题,好久没碰到偏移量的题目了....
select
user_id, max(rn) biggest_window
from 
(
select
user_id,
datediff(
lead(visit_date,1,"2021-01-01") over(partition by user_id order by visit_date ) ,visit_date) rn
from
UserVisits
) t1
group by user_id
order by user_id

练习题 14

141.苹果和橘子的个数

编写 SQL 语句,查询每个大箱子中苹果和橘子的个数。如果大箱子中包含小盒子,还应当包含小盒子中苹果和橘子的个数

表: Boxes

text
+--------------+------+
| Column Name  | Type |
+--------------+------+
| box_id       | int  |
| chest_id     | int  |
| apple_count  | int  |
| orange_count | int  |
+--------------+------+

box_id 是该表的主键。
chest_id 是 chests 表的外键。
该表包含大箱子 (box) 中包含的苹果和橘子的个数。每个大箱子中可能包含一个小盒子 (chest) ,小盒子中也包含若干苹果和橘子。
 

表: Chests

text
+--------------+------+
| Column Name  | Type |
+--------------+------+
| chest_id     | int  |
| apple_count  | int  |
| orange_count | int  |
+--------------+------+

chest_id 是该表的主键。
该表包含小盒子的信息,以及小盒子中包含的苹果和橘子的个数。
 

编写 SQL 语句,查询每个大箱子中苹果和橘子的个数。如果大箱子中包含小盒子,还应当包含小盒子中苹果和橘子的个数。

以任意顺序返回结果表。

查询结果的格式如下示例所示:

 

Boxes 表:

text
+--------+----------+-------------+--------------+
| box_id | chest_id | apple_count | orange_count |
+--------+----------+-------------+--------------+
| 2      | null     | 6           | 15           |
| 18     | 14       | 4           | 15           |
| 19     | 3        | 8           | 4            |
| 12     | 2        | 19          | 20           |
| 20     | 6        | 12          | 9            |
| 8      | 6        | 9           | 9            |
| 3      | 14       | 16          | 7            |
+--------+----------+-------------+--------------+

Chests 表:

text
+----------+-------------+--------------+
| chest_id | apple_count | orange_count |
+----------+-------------+--------------+
| 6        | 5           | 6            |
| 14       | 20          | 10           |
| 2        | 8           | 8            |
| 3        | 19          | 4            |
| 16       | 19          | 19           |
+----------+-------------+--------------+

结果表:

text
+-------------+--------------+
| apple_count | orange_count |
+-------------+--------------+
| 151         | 123          |
+-------------+--------------+

大箱子 2 中有 6 个苹果和 15 个橘子。
大箱子 18 中有 4 + 20 (在小盒子中) = 24 个苹果和 15 + 10 (在小盒子中) = 25 个橘子。
大箱子 19 中有 8 + 19 (在小盒子中) = 27 个苹果和 4 + 4 (在小盒子中) = 8 个橘子。
大箱子 12 中有 19 + 8 (在小盒子中) = 27 个苹果和 20 + 8 (在小盒子中) = 28 个橘子。
大箱子 20 中有 12 + 5 (在小盒子中) = 17 个苹果和 9 + 6 (在小盒子中) = 15 个橘子。
大箱子 8 中有 9 + 5 (在小盒子中) = 14 个苹果和 9 + 6 (在小盒子中) = 15 个橘子。
大箱子 3 中有 16 + 20 (在小盒子中) = 36 个苹果和 7 + 10 (在小盒子中) = 17 个橘子。
苹果的总个数 = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151
橘子的总个数 = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123

sql
简单题,注意null+ ? = null
select
sum(ifnull(t1.apple_count,0) + ifnull(t2.apple_count,0)) apple_count  , 
sum(ifnull(t1.orange_count,0) + ifnull(t2.orange_count,0)) orange_count
from
Boxes t1
left join Chests t2 on t1.chest_id = t2.chest_id

142.求关注者的数量

写出 SQL 语句,对于每一个用户,返回该用户的关注者数量

表: Followers

text
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| follower_id | int  |
+-------------+------+

(user_id, follower_id) 是这个表的主键。
该表包含一个关注关系中关注者和用户的编号,其中关注者关注用户。
写出 SQL 语句,对于每一个用户,返回该用户的关注者数量。

按 user_id 的顺序返回结果表。

查询结果的格式如下示例所示:

 

Followers 表:

text
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| 0       | 1           |
| 1       | 0           |
| 2       | 0           |
| 2       | 1           |
+---------+-------------+

结果表:

text
+---------+----------------+
| user_id | followers_count|
+---------+----------------+
| 0       | 1              |
| 1       | 1              |
| 2       | 2              |
+---------+----------------+

0 的关注者有 {1}
1 的关注者有 {0}
2 的关注者有 {0,1}

sql
--简单题,直接count(*)即可
select
user_id,count(distinct follower_id ) followers_count
from 
Followers
group by user_id
order by user_id

143.向每个员工报告的员工人数

编写一个SQL查询来报告id和所有经理的姓名、直接向他们报告的员工人数,以及四舍五入到最接近的整数的报告的平均年龄。

text
Table: Employees

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| employee_id | int      |
| name        | varchar  |
| reports_to  | int      |
| age         | int      |
+-------------+----------+
employee_id is the primary key for this table.
This table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null). 
 

For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.

Write an SQL query to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer.

Return the result table ordered by employee_id.

The query result format is in the following example:

 

Employees table:
+-------------+---------+------------+-----+
| employee_id | name    | reports_to | age |
+-------------+---------+------------+-----+
| 9           | Hercy   | null       | 43  |
| 6           | Alice   | 9          | 41  |
| 4           | Bob     | 9          | 36  |
| 2           | Winston | null       | 37  |
+-------------+---------+------------+-----+

Result table:
+-------------+-------+---------------+-------------+
| employee_id | name  | reports_count | average_age |
+-------------+-------+---------------+-------------+
| 9           | Hercy | 2             | 39          |
+-------------+-------+---------------+-------------+
Hercy has 2 people report directly to him, Alice and Bob. Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest integer.
sql
--简单题
select
t1.employee_id,t1.name,
count(2) as  reports_count,
round(avg(t2.age)) average_age 
from 
Employees t1 
join Employees t2 on t1. employee_id = t2.reports_to
group by t1.employee_id,t1.name
order by  employee_id

144.找出每个员工花费的总时间

编写一个SQL查询,以分钟为单位计算每个员工每天在办公室花费的总时间

sql
Table: Employees

+-------------+------+
| Column Name | Type |
+-------------+------+
| emp_id      | int  |
| event_day   | date |
| in_time     | int  |
| out_time    | int  |
+-------------+------+
(emp_id, event_day, in_time) is the primary key of this table.
The table shows the employees' entries and exits in an office.
event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office.
in_time and out_time are between 1 and 1440.
It is guaranteed that no two events on the same day intersect in time, and in_time < out_time.
 

Write an SQL query to calculate the total time in minutes spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time - in_time.

Return the result table in any order.

The query result format is in the following example:

Employees table:
+--------+------------+---------+----------+
| emp_id | event_day  | in_time | out_time |
+--------+------------+---------+----------+
| 1      | 2020-11-28 | 4       | 32       |
| 1      | 2020-11-28 | 55      | 200      |
| 1      | 2020-12-03 | 1       | 42       |
| 2      | 2020-11-28 | 3       | 33       |
| 2      | 2020-12-09 | 47      | 74       |
+--------+------------+---------+----------+
Result table:
+------------+--------+------------+
| day        | emp_id | total_time |
+------------+--------+------------+
| 2020-11-28 | 1      | 173        |
| 2020-11-28 | 2      | 30         |
| 2020-12-03 | 1      | 41         |
| 2020-12-09 | 2      | 27         |
+------------+--------+------------+
Employee 1 has three events: two on day 2020-11-28 with a total of (32 - 4) + (200 - 55) = 173, and one on day 2020-12-03 with a total of (42 - 1) = 41.
Employee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, and one on day 2020-12-09 with a total of (74 - 47) = 27.
sql
--简单题
select
event_day day ,
emp_id ,
sum(out_time - in_time) total_time
from 
Employees
group by 1,2

145.Leetflex禁止帐户

编写一个SQL查询来查找应该从Leetflex中禁止的帐户的account_id。如果一个帐户在某一时刻从两个不同的IP地址登录,应该被禁止。

sql
Table: LogInfo

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| account_id  | int      |
| ip_address  | int      |
| login       | datetime |
| logout      | datetime |
+-------------+----------+
There is no primary key for this table, and it may contain duplicates.
The table contains information about the login and logout dates of Leetflex accounts. It also contains the IP address from which the account logged in and out.
It is guaranteed that the logout time is after the login time.
 

Write an SQL query to find the account_id of the accounts that should be banned from Leetflex. An account should be banned if it was logged in at some moment from two different IP addresses.

Return the result table in any order.

The query result format is in the following example:

 

LogInfo table:
+------------+------------+---------------------+---------------------+
| account_id | ip_address | login               | logout              |
+------------+------------+---------------------+---------------------+
| 1          | 1          | 2021-02-01 09:00:00 | 2021-02-01 09:30:00 |
| 1          | 2          | 2021-02-01 08:00:00 | 2021-02-01 11:30:00 |
| 2          | 6          | 2021-02-01 20:30:00 | 2021-02-01 22:00:00 |
| 2          | 7          | 2021-02-02 20:30:00 | 2021-02-02 22:00:00 |
| 3          | 9          | 2021-02-01 16:00:00 | 2021-02-01 16:59:59 |
| 3          | 13         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
| 4          | 10         | 2021-02-01 16:00:00 | 2021-02-01 17:00:00 |
| 4          | 11         | 2021-02-01 17:00:00 | 2021-02-01 17:59:59 |
+------------+------------+---------------------+---------------------+

Result table:
+------------+
| account_id |
+------------+
| 1          |
| 4          |
+------------+
Account ID 1 --> The account was active from "2021-02-01 09:00:00" to "2021-02-01 09:30:00" with two different IP addresses (1 and 2). It should be banned.
Account ID 2 --> The account was active from two different addresses (6, 7) but in two different times.
Account ID 3 --> The account was active from two different addresses (9, 13) on the same day but they do not intersect at any moment.
Account ID 4 --> The account was active from "2021-02-01 17:00:00" to "2021-02-01 17:00:00" with two different IP addresses (10 and 11). It should be banned.
sql
--简单题
select
distinct t1.account_id 
from
LogInfo t1
join LogInfo t2 on t1.account_id = t2.account_id and t1.login < t2.login and t1.ip_address <> t2.ip_address
where (t2.logout - t1.login) <  (t1.logout + t2.logout - t1.login - t2.login) or t1.logout = t2.login
sql
--为什么这个快??
select
distinct l1.account_id
from
loginfo l1 join loginfo l2
on l1.account_id = l2.account_id and l1.ip_address <> l2.ip_address
and l1.login between l2.login and l2.logout

146.可回收低脂产品

编写一个SQL查询来查找低脂肪和可回收产品的id。

sql
Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| low_fats    | enum    |
| recyclable  | enum    |
+-------------+---------+
product_id is the primary key for this table.
low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.
 

Write an SQL query to find the ids of products that are both low fat and recyclable.

Return the result table in any order.

The query result format is in the following example:

 

Products table:
+-------------+----------+------------+
| product_id  | low_fats | recyclable |
+-------------+----------+------------+
| 0           | Y        | N          |
| 1           | Y        | Y          |
| 2           | N        | Y          |
| 3           | Y        | Y          |
| 4           | N        | N          |
+-------------+----------+------------+
Result table:
+-------------+
| product_id  |
+-------------+
| 1           |
| 3           |
+-------------+
Only products 1 and 3 are both low fat and recyclable.
sql
select product_id from Products where low_fats ="Y" and recyclable ="Y"

147.行程和用户

写一段 SQL 语句查出 "2013-10-01" 至 "2013-10-03" 期间非禁止用户(乘客和司机都必须未被禁止)的取消率。非禁止用户即 Banned 为 No 的用户,禁止用户即 Banned 为 Yes 的用户。
取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。
返回结果表中的数据可以按任意顺序组织。其中取消率 Cancellation Rate 需要四舍五入保留 两位小数

表:Trips

text
+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| Id          | int      |
| Client_Id   | int      |
| Driver_Id   | int      |
| City_Id     | int      |
| Status      | enum     |
| Request_at  | date     |     
+-------------+----------+

Id 是这张表的主键。
这张表中存所有出租车的行程信息。每段行程有唯一 Id ,其中 Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外键。
Status 是一个表示行程状态的枚举类型,枚举成员为(‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’) 。
 

表:Users

text
+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| Users_Id    | int      |
| Banned      | enum     |
| Role        | enum     |
+-------------+----------+

Users_Id 是这张表的主键。
这张表中存所有用户,每个用户都有一个唯一的 Users_Id ,Role 是一个表示用户身份的枚举类型,枚举成员为 (‘client’, ‘driver’, ‘partner’) 。
Banned 是一个表示用户是否被禁止的枚举类型,枚举成员为 (‘Yes’, ‘No’) 。
 

写一段 SQL 语句查出 "2013-10-01" 至 "2013-10-03" 期间非禁止用户(乘客和司机都必须未被禁止)的取消率。非禁止用户即 Banned 为 No 的用户,禁止用户即 Banned 为 Yes 的用户。

取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数)。

返回结果表中的数据可以按任意顺序组织。其中取消率 Cancellation Rate 需要四舍五入保留 两位小数 。

 

查询结果格式如下例所示:

Trips 表:

text
+----+-----------+-----------+---------+---------------------+------------+
| Id | Client_Id | Driver_Id | City_Id | Status              | Request_at |
+----+-----------+-----------+---------+---------------------+------------+
| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |
| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |
| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |
| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |
| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |
| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |
| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |
| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |
| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |
| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |
+----+-----------+-----------+---------+---------------------+------------+

Users 表:

text
+----------+--------+--------+
| Users_Id | Banned | Role   |
+----------+--------+--------+
| 1        | No     | client |
| 2        | Yes    | client |
| 3        | No     | client |
| 4        | No     | client |
| 10       | No     | driver |
| 11       | No     | driver |
| 12       | No     | driver |
| 13       | No     | driver |
+----------+--------+--------+

Result 表:

text
+------------+-------------------+
| Day        | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 | 0.33              |
| 2013-10-02 | 0.00              |
| 2013-10-03 | 0.50              |
+------------+-------------------+

2013-10-01:

  • 共有 4 条请求,其中 2 条取消。
  • 然而,Id=2 的请求是由禁止用户(User_Id=2)发出的,所以计算时应当忽略它。
  • 因此,总共有 3 条非禁止请求参与计算,其中 1 条取消。
  • 取消率为 (1 / 3) = 0.33
    2013-10-02:
  • 共有 3 条请求,其中 0 条取消。
  • 然而,Id=6 的请求是由禁止用户发出的,所以计算时应当忽略它。
  • 因此,总共有 2 条非禁止请求参与计算,其中 0 条取消。
  • 取消率为 (0 / 2) = 0.00
    2013-10-03:
  • 共有 3 条请求,其中 1 条取消
  • 然而,Id=8 的请求是由禁止用户发出的,所以计算时应当忽略它
  • 因此,总共有 2 条非禁止请求参与计算,其中 1 条取消。
  • 取消率为 (1 / 2) = 0.50
sql
--简单题
select request_at as Day,
round(sum(if(status != 'completed',1,0))/count(1),2) as 'Cancellation Rate' 
from Trips
where 
request_at between "2013-10-01" and "2013-10-03"
and
client_id not in (select users_id from users where banned = "Yes")
group by request_at;

148.第N高的薪水

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

text
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。

text
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+
sql
--简单题
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
      select distinct Salary
      from(
      select Salary ,dense_rank()over(order by Salary desc ) as r 
      from Employee) t
      where r=N
  );
END

补充两道SQL题,凑整数

149.如果为null,则取上一个不为null的值

image.png

方案一
首先把不为null的数据取出来放在数组中,接着对增加一个字段,如果为null,那么就为0否则为1 ,接着原表开窗(sum()) 取数组中arr[rn-1] 的数据

sql
price_date,price 表:price

with x as (
select 
collect_list(price) as arr 
from 
price
where price is not null 
),
y as (
select 
price_date,
price,
sum(label) over(order by price_date) as rn 
from 
(
select
price_date,
price,
if(price is null,0,1) as  label
from
price 
) o 
) 
select 
price_date, arr[rn-1] as price
from 
y 
text
+----------+-----+
|price_date|price|
+----------+-----+
|2019-09-25|23.23|
|2019-09-26|32.54|
|2019-09-27|34.55|
|2019-09-28|34.55|
|2019-09-29|34.55|
|2019-09-30|54.22|
|2019-10-01|54.22|
|2019-10-02|54.22|
|2019-10-03|54.22|
|2019-10-04|54.22|
|2019-10-05|54.22|
|2019-10-06|54.22|
|2019-10-07|54.22|
|2019-10-08|33.80|
|2019-10-09|33.83|

方案二

首先排除为null的,把时间lead上移.如果原表的时间在这个区间,那么就取这个区间的时间
发现join重复数据,采用了过滤为null的值,能否采用其他方法

sql
with x as (
select
price_date,price,
lead(price_date,1,price_date) over(order by price_date) as price_date1
from
(
select  -- 查找出price不为null的行
price_date,price
from
pricetable
where price != 'null'
) o
)
select
price_date,price
from
(
select
pricetable.price_date,
x.price
from
pricetable,x
where pricetable.price = 'null' and  (pricetable.price_date between x.price_date and x.price_date1)

union all

select
price_date,price
from
pricetable
where price != 'null'
) t1
order by  price_date

150.指标分析

image.png

sql
create table  TEST(
     DEP_CODE varchar(10),
     ITEM_CODE varchar(10),
     ITEM_VALUE int
);
insert into TEST values ('单位一','A',100);
insert into TEST values ('单位二','A',200);
insert into TEST values ('单位一','B',300);
insert into TEST values ('单位二','B',300);
insert into TEST values ('单位一','C',350);
insert into TEST values ('单位二','C',300);

select
    DEP_CODE,
    ITEM_CODE,
    ITEM_VALUE
from
    TEST
UNION ALL

select
    DEP_CODE,
    'D'  as ITEM_CODE,
    sum(if(ITEM_CODE = 'C',-ITEM_VALUE,ITEM_VALUE)) as  ITEM_VALUE
from
    TEST
group by  DEP_CODE

练习题 15

leedcode高频题,半年前写过再写一遍.....

151.组合两张表

编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:

表1: Person

text
+-------------+---------+
| 列名         | 类型     |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+

PersonId 是上表主键
表2: Address

text
+-------------+---------+
| 列名         | 类型    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+

AddressId 是上表主键
 

编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:

 

FirstName, LastName, City, State

sql
--简单题
select
FirstName,LastName, City, State 
from Person t1 left join  Address t2 
on t1.PersonId  = t2. PersonId   

152.第二高的薪水(自连接)

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

text
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

一开始我是这ifnull(?,null) 发现为空,where条件返回空,如果是聚合函数则不存在就会返回null

sql
select
ifnull(max(Salary),null)  SecondHighestSalary
from 
(
select
Salary,
dense_rank() over(order by Salary desc ) rn 
from
Employee
) t1
where rn =2

其他方法找到最大的子查询取max最大的但是小于max

sql
select max(Salary) SecondHighestSalary
from employee
where
salary<(select max(salary) from employee)

limit分页

sql
select (select distinct salary from Employee order by salary desc limit 1,1) as SecondHighestSalary 

自连接

sql
select
(
    select e1.Salary
    from Employee e1,Employee e2
    where e1.Salary<=e2.Salary
    group by e1.Salary
    having count(distinct e2.Salary)=2
) as SecondHighestSalary

153.分数排名

编写一个 SQL 查询来实现分数排名

编写一个 SQL 查询来实现分数排名。

如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

text
+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

text
+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 Rank

sql
--简单题
select
Score,
dense_rank() over(order by Score desc  ) `Rank`
from 
Scores
sql
--学习一下自连接,面试常问
select s1.Score,count(distinct(s2.score)) `Rank`
from
Scores s1,Scores s2
where
s1.score<=s2.score
group by s1.Id
order by `Rank`

154.连续出现的数字

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

表:Logs

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+

id 是这个表的主键。
 

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

返回的结果表中的数据可以按 任意顺序 排列。

 

查询结果格式如下面的例子所示:

 

Logs 表:

text
+----+-----+
| Id | Num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+

Result 表:

text
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

1 是唯一连续出现至少三次的数字。

sql
--不需要判断id的偏移量,因为样本id是连续的
select
distinct Num ConsecutiveNums
from
(
select
Id,
Num,
lag(Num,1) over() as lag_num,
lag(Id,1) over() as lag_id,
lead(Num,1) over() as lead_num,
lead(Id,1) over() as lead_id
from 
Logs
) t1
where Id = lag_id + 1 and Id = lead_id-1 and Num = lag_num and Num =lead_num
sql
--一个巧妙的方法
SELECT DISTINCT Num AS ConsecutiveNums FROM Logs 
WHERE (Id+1, Num) IN (SELECT * FROM Logs)
AND (Id+2, Num) IN (SELECT * FROM Logs)

类似于连续登陆案例

sql
select distinct Num as ConsecutiveNums
from (select Num,abs(Id+1-(dense_rank() over(partition by Num  order by Id)) ) as temp 
        from Logs ) as t 
group by Num,temp
having count(temp )>=3

155.超过经理收入的员工

给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

text
+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

text
+----------+
| Employee |
+----------+
| Joe      |
+----------+
sql
--简单题
select 
t1.Name Employee
from 
Employee t1 
join Employee t2 on t1.ManagerId = t2.Id 
where t1.Salary > t2.Salary

使用子查询,首先获取是经理的员工,然后在比较收入

156查找重复的邮箱

编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

text
编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

示例:

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+
根据以上输入,你的查询应返回以下结果:

+---------+
| Email   |
+---------+
| a@b.com |
sql
select 
Email
from 
Person
group by Email
having count(1) >1

157.从不订购的客户

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

text
+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Orders 表:

text
+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

例如给定上述表格,你的查询应返回:

text
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+
sql
简单题
select 
t1.Name Customers
from 
Customers t1 left join Orders t2 on t1.Id = t2.CustomerId
where t2.CustomerId is null 
sql
子查询
SELECT Name 'Customers'
FROM Customers
WHERE Id NOT IN(
    SELECT CustomerId 
    FROM Orders
)

158.部门工资最高的员工

编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)

Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。

text
+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Jim   | 90000  | 1            |
| 3  | Henry | 80000  | 2            |
| 4  | Sam   | 60000  | 2            |
| 5  | Max   | 90000  | 1            |
+----+-------+--------+--------------+

Department 表包含公司所有部门的信息。

text
+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)。

text
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Jim      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

解释:

Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。

sql
--简单题
select
Department,Employee,Salary 
from 
(
select
t1.Name Department, t2.Name Employee,Salary,
rank() over(partition by t1.Name order by Salary desc ) rn 
from Department t1 join Employee t2 on t1.Id = t2.DepartmentId
) s1 
where rn =1
sql
子查询
select 
    d.Name as Department,
    e.Name as Employee,
    e.Salary 
from 
    Employee e,Department d 
where
    e.DepartmentId=d.id 
    and
    (e.Salary,e.DepartmentId) in (select max(Salary),DepartmentId from Employee group by DepartmentId);

159.工资前三高的员工

编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:

Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。

text
+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+

Department 表包含公司所有部门的信息。

text
+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:

text
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+

解释:

IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。

sql
简单题窗口
select Department, Employee, Salary
from (
    select d.Name as Department, e.Name as Employee, e.Salary as Salary, 
dense_rank() over ( partition by DepartmentId order by Salary desc) as rk
    from Employee as e, Department as d
    where e.DepartmentId = d.Id
) m
where rk <= 3;
sql
select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee as e left join Department as d 
on e.DepartmentId = d.Id
where e.Id in
(
    select e1.Id
    from Employee as e1 left join Employee as e2
    on e1.DepartmentId = e2.DepartmentId and e1.Salary < e2.Salary
    group by e1.Id
    having count(distinct e2.Salary) <= 2
)
and e.DepartmentId in (select Id from Department)
order by d.Id asc,e.Salary desc

170.删除重复的邮箱

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

text
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+

Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

text
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

提示:

执行 SQL 之后,输出是整个 Person 表。
使用 delete 语句。

sql
delete p1 from (person as p1 left join person as p2 on p1.email = p2.email) where p1.id > p2.id ;
sql
DELETE from Person 
Where Id not in (
    Select Id 
    From(
    Select MIN(Id) as id
    From Person 
    Group by Email
   ) t
)

练习题 16:牛客网错题难题再写一遍

牛客网的题目都是截图,我懒得截图了直接标明题目,请在牛客网中查找实际序号吧...
下面的题目都是之前出于各种原因在笔记上的题目,再写一遍希望有所收获

161.获取当前薪水第二多的员工(18)

使用子查询来获取,查找出最大的薪资,然后在剩余的薪资中查找出最大的即是第二大的值
序列函数也可以

sql
select 
employees.emp_no,salary,last_name,first_name
from 
employees join salaries on employees.emp_no = salaries.emp_no
where salary = (
select
max(salary)
from 
salaries
where salary < (select max(salary) from   salaries)
) 

162.统计各部门工资条数(22)

我为什么会记录这道题目???这道题目可以考察更多的内容,比如说涨工资的情况等

sql
select
t1.dept_no ,t1.dept_name,count(salary) as `sum`
from
departments t1 join  dept_emp t2 on t1.dept_no = t2.dept_no
               join  salaries t3 on t2.emp_no = t3.emp_no
group by t1.dept_no ,t1.dept_name
order by t1.dept_no

163.对所有员工薪水进行排名(23)☆

自连接分数排名,使用窗口也可(rank),学习使用自连接解决窗口问题,比如说sum()开窗,使用having来过滤即可,比如这题的序列排名,还有分组topN问题,使用自连接限制where的条件即可(结合group by 分组获取的条数来判断),面试常问!!!!!!

sql
select
t1.emp_no ,t1.salary,count(distinct t2.salary) as t_rank 
from
salaries t1 cross join salaries t2 
where t1.salary <= t2.salary
group by t1.emp_no ,t1.salary
order by t_rank

164.获取员工的薪水比其领导还高的员工相关信息(25)

第一次写的比这个复杂??第二次写还是不够好,看了一下评论区可以采用再join 一张薪水表来实现,可能速度会快一点?然而并不,不知道在大数据中哪个快一点??

sql
select
t1.emp_no,t3.emp_no  manager_no , t2.salary  emp_salary , t3.salary  manager_salary
from
dept_emp t1 join salaries t2 on t1.emp_no = t2.emp_no
join 
(
select
dept_manager.dept_no as dept_no,salary,dept_manager.emp_no emp_no
from
dept_manager join salaries on dept_manager.emp_no = salaries.emp_no
) t3 
on t1.dept_no = t3.dept_no
where t2.salary > t3.salary
sql
select de.emp_no, dm.emp_no as manager_no,
s1.salary as emp_salary, s2.salary as manager_salary
from dept_emp de, dept_manager dm, salaries s1, salaries s2
where de.dept_no = dm.dept_no
and de.emp_no = s1.emp_no
and dm.emp_no = s2.emp_no
and s1.salary > s2.salary

165.找出没有分类的电影id和其他信息(29)

这题我以前写错了....这题考察在left join 条件下 on where 条件的区别,on会返回没有匹配上的行(也就是说始终返回左边的数据),而where会过滤null的值,还有这题也考察了 is null != null的区别,!=null始终会返回true,所以尽量使用is (not) null

sql
select
t1.film_id ,title
from 
film t1 left join film_category t2 on t1.film_id = t2.film_id
where category_id is null

166.删除重复emp_no的记录,只保留最小id的记录(42)

这题目在leedcode中也有学习delete语法,牛客网还有其他的DML语法练习题,注意delete在mysql中的语法,注意方法二中的表达

sql
delete from titles_test
where id not in (
  select * from (
select
min(id)
from titles_test
group by emp_no ) l ) 
sql
delete t1  from titles_test t1 , titles_test t2
where t1.emp_no = t2.emp_no and t1.id > t2.id

167.牛客新登录用户的次日成功的留存率(68)

对于这种留存率的问题,就是指标的处理,一般采用的函数有lag/lead,不同窗口大小下的开窗进行比较等,以后专门有一篇博客来示例这种指标值
但是这题....过于简单...就是连续登陆的变形题,序列函数即可...不用窗口更简单

sql
select
round(count(distinct t1.user_id ) /(select count(distinct user_id) from login ) ,3)  p
from 
(
select
user_id,min(date) as date
from 
login
group by user_id
) t1 
join login on t1.user_id = login.user_id
where datediff(login.date,t1.date) =1

评论区:查询最小的天数+1 where联合查询看是否存在这一天

sql
select 
round(count(distinct user_id)*1.0/(select count(distinct user_id) from login) ,3)
from login
where (user_id,date)
in (select user_id,DATE_ADD(min(date),INTERVAL 1 DAY) from login group by user_id);

168.统计牛客每个日期登录新用户个数(69)(窗口写法)

注意sum/count与if一起用的时候要注意0的使用count也会+1所以这里是sum,如果要使用count则应该把0改为null然后在外面嵌套一个ifnull

sql
select
date,
sum(if(rn = 1,1,0)) new 
from 
(
select 
date,rank() over(partition by user_id order by date) rn 
from 
login
) t1
group by date

也可以使用老方法区每个人最早登录的时间然后按照时间group by ,接着获取全部的时间,不能join上的就为0

sql
select a.all_date as date, ifnull(count(b.user_id),0) as new
from
    (select distinct(date) as all_date
    from login) as a
left join
    (select user_id, min(date) as reg_date
    from login
    group by user_id) as b 
on a.all_date = b.reg_date
group by a.all_date

169.每个日期新用户的次日留存率(70)

使用union 来代替一次join连接

sql
(
select
t1.date ,round(count(t2.user_id) / count(t1.user_id) ,3)  p
from 
(
select
user_id,min(date) as date
from 
login
group by user_id
) t1 
left join login t2 on datediff(t1.date,t2.date) = -1  and t1.user_id = t2.user_id
group by t1.date
)
union 
select date,0.000 p from login 
where date not in (select min(date)
from login
group by user_id)
order by date
sql
(
select
t1.date ,round(count(t2.user_id) / count(t1.user_id) ,3)  p
from 
(
select
user_id,min(date) as date
from 
login
group by user_id
) t1 
left join login t2 on DATE_SUB(t1.date,INTERVAL - 1 DAY) = t2.date  and t1.user_id = t2.user_id
group by t1.date
)
union 
select date,0.000 p from login 
where date not in (select min(date)
from login
group by user_id)
order by date

170.请你找出每个岗位分数排名前2的用户(74)

分组topN的问题,使用自连接having过滤来获取topN,二是使用窗口来求

sql
select
grade.id,name,s1.score
from 
grade
join 
(
select
t1.language_id,t1.score
from
grade t1 join grade t2 on t1.language_id = t2.language_id and t1.score <= t2.score
group by t1.language_id,t1.score
having count(distinct t2.score) <= 2
) s1 
on grade.language_id = s1.language_id and grade.score = s1.score 
join 
language 
on grade.language_id = language.id
order by name,score desc 
sql
select gl.id,gl.name,gl.score
from (select g.id,l.name,g.score,
dense_rank() over(partition by g.language_id order by g.score desc) as ran
from grade g  join language l
on g.language_id = l.id) gl
where gl.ran < 3
order by gl.name

171.中位数位置的范围(75)

第76同这一题都是求中位数,leedcode中也有类似的题目,使用两个序列函数来求,值得注意的是如果排两个,要排序的字段有重复的,按照字典顺序顺序和逆序会乱序,要指定第二个人字段desc/asc
这道题目之前写复杂了,直接借助于round的四舍五入来求即可..不需要使用case when 来分类讨论

sql
select
job,round(count(score)/2) start ,round((count(score) +1) /2) end
from
grade
group by job
order by job

一些函数的使用

text
limit的用法 limit 1,2 从位移1截取取2个
text
length( '10,A,B') - length(REPLACE( '10,A,B',',',''));
sql
--负数的使用,从后面开始查询
select 
first_name
from
employees
order by  substr(first_name,-2,2) 
sql
--group_concat函数的使用大致等同于concat和collect_list的结合
select 
dept_no,
group_concat(emp_no)
from
dept_emp
group  by dept_no
sql
--limit的分页功能
select *
from employees
limit 5, 5;
``

练习题 17:Summary-of-knowledge(1)

一些SQL关键字的使用技巧
一些SQL题的一题多解
来源于 leedcode 知乎 牛客等

171.自连接实现窗口用法

Table: Activity

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+

(player_id,event_date)是此表的主键。
这张表显示了某些游戏的玩家的活动情况。
每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0 )。
 
编写一个 SQL 查询,同时报告每组玩家和日期,以及玩家到目前为止玩了多少游戏。也就是说,在此日期之前玩家所玩的游戏总数。详细情况请查看示例。

查询结果格式如下所示:

Activity table:

text
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-05-02 | 6            |
| 1         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result table:

text
+-----------+------------+---------------------+
| player_id | event_date | games_played_so_far |
+-----------+------------+---------------------+
| 1         | 2016-03-01 | 5                   |
| 1         | 2016-05-02 | 11                  |
| 1         | 2017-06-25 | 12                  |
| 3         | 2016-03-02 | 0                   |
| 3         | 2018-07-03 | 5                   |
+-----------+------------+---------------------+

对于 ID 为 1 的玩家,2016-05-02 共玩了 5+6=11 个游戏,2017-06-25 共玩了 5+6+1=12 个游戏。
对于 ID 为 3 的玩家,2018-07-03 共玩了 0+5=5 个游戏。
请注意,对于每个玩家,我们只关心玩家的登录日期。

自连接

sql
使用自连接也能实现序列函数/分组topN等问题
select
t1.player_id , t1.event_date,sum(t2.games_played) games_played_so_far  
from 
Activity t1 join Activity t2
on t1.player_id = t2. player_id    and t1.event_date >= t2.event_date
group by t1.player_id , t1.event_date
sql
示例:排序序列函数自连接实现,来源牛客网23题
select
t1.emp_no ,t1.salary,count(distinct t2.salary) as t_rank 
from
salaries t1 cross join salaries t2 
where t1.salary <= t2.salary
group by t1.emp_no ,t1.salary
order by t_rank
sql
示例:分组topN自连接实现,来源牛客网74题
select
t1.language_id,t1.score
from
grade t1 join grade t2 on t1.language_id = t2.language_id and t1.score <= t2.score
group by t1.language_id,t1.score
having count(distinct t2.score) <= 2
sql
示例:sum窗口大小统计,来源leedcode579题
SELECT
  a.Id AS id, a.Month AS month,SUM(b.Salary) AS Salary
FROM
  Employee a, Employee b
WHERE a.Id = b.Id 
AND a.Month >= b.Month
AND a.Month < b.Month+3
AND (a.Id, a.Month) NOT IN (SELECT Id, MAX(Month) FROM Employee GROUP BY Id)
GROUP BY a.Id, a.Month
ORDER BY a.Id, a.Month DESC
sql
-- 自连接获取第二个 having sum(o1.order_date > o2.order_date) = 1 leedcode1159
//使用sum()统计比当前订单日期更早的订单数,若为1,说明当前订单是对应用户卖
//出的第二单
select user_id seller_id, if(favorite_brand = item_brand, 'yes', 'no') 2nd_item_fav_brand
from users left join (
    select seller_id, item_brand
    from (
        select o1.seller_id, o1.item_id
        from orders o1 join orders o2
        on o1.seller_id = o2.seller_id
        group by o1.order_id
        having sum(o1.order_date > o2.order_date) = 1
    ) o join items i
    on o.item_id = i.item_id
) tmp
on user_id = seller_id

172.正序和逆序

Numbers 表保存数字的值及其频率。

text
+----------+-------------+
|  Number  |  Frequency  |
+----------+-------------|
|  0       |  7          |
|  1       |  1          |
|  2       |  3          |
|  3       |  1          |
+----------+-------------+

在此表中,数字为 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3,所以中位数是 (0 + 0) / 2 = 0。

text
+--------+
| median |
+--------|
| 0.0000 |
+--------+

请编写一个查询来查找所有数字的中位数并将结果命名为 median

中位数数学含义,这里的sum求的是number的位置

sql
select avg(number) as median
from
(select Number, frequency,
        sum(frequency) over(order by number asc) as total,
        sum(frequency) over(order by number desc) as total1
from Numbers
order by number asc)as a
where total>=(select sum(frequency) from Numbers)/2
and total1>=(select sum(frequency) from Numbers)/2

下面一题同样体现了中位数的数学意义,使用两个序列函数正序和逆序就能解决问题,在牛客网的最后一题也是这个思路

Employee 表包含所有员工。Employee 表有三列:员工Id,公司名和薪水。

text
+-----+------------+--------+
|Id   | Company    | Salary |
+-----+------------+--------+
|1    | A          | 2341   |
|2    | A          | 341    |
|3    | A          | 15     |
|4    | A          | 15314  |
|5    | A          | 451    |
|6    | A          | 513    |
|7    | B          | 15     |
|8    | B          | 13     |
|9    | B          | 1154   |
|10   | B          | 1345   |
|11   | B          | 1221   |
|12   | B          | 234    |
|13   | C          | 2345   |
|14   | C          | 2645   |
|15   | C          | 2645   |
|16   | C          | 2652   |
|17   | C          | 65     |
+-----+------------+--------+

请编写SQL查询来查找每个公司的薪水中位数。挑战点:你是否可以在不使用任何内置的SQL函数的情况下解决此问题。

text
+-----+------------+--------+
|Id   | Company    | Salary |
+-----+------------+--------+
|5    | A          | 451    |
|6    | A          | 513    |
|12   | B          | 234    |
|9    | B          | 1154   |
|14   | C          | 2645   |
+-----+------------+--------+

方法一,注意窗口要指定两个字段

sql
select a.Id,a.Company,a.Salary
from
(select Id,Company,Salary,
cast(row_number()  over(partition by Company order  by salary desc,Id desc ) as signed ) as 'id1',
cast(row_number()  over(partition by Company order  by salary asc,Id asc ) as signed) as 'id2'
from  Employee) a
where abs(a.id1-a.id2) =1 or abs(a.id1-a.id2)=0

方法二,中位数的数学含义

sql
select Id,Company,Salary
from
(
select Id,Company,Salary, 
row_number()over(partition by Company order by Salary)as ranking,
count(Id) over(partition by Company)as cnt
from Employee
)a
where ranking>=cnt/2 and ranking<=cnt/2+1

173.窗口大小

Employee 表保存了一年内的薪水信息。

请你编写 SQL 语句,对于每个员工,查询他除最近一个月(即最大月)之外,剩下每个月的近三个月的累计薪水(不足三个月也要计算)。

结果请按 Id 升序,然后按 Month 降序显示。

 

示例:
输入:

text
| Id | Month | Salary |
|----|-------|--------|
| 1  | 1     | 20     |
| 2  | 1     | 20     |
| 1  | 2     | 30     |
| 2  | 2     | 30     |
| 3  | 2     | 40     |
| 1  | 3     | 40     |
| 3  | 3     | 60     |
| 1  | 4     | 60     |
| 3  | 4     | 70     |

输出:

text
| Id | Month | Salary |
|----|-------|--------|
| 1  | 3     | 90     |
| 1  | 2     | 50     |
| 1  | 1     | 20     |
| 2  | 1     | 20     |
| 3  | 3     | 100    |
| 3  | 2     | 40     |

解释:

员工 '1' 除去最近一个月(月份 '4'),有三个月的薪水记录:月份 '3' 薪水为 40,月份 '2' 薪水为 30,月份 '1' 薪水为 20。

所以近 3 个月的薪水累计分别为 (40 + 30 + 20) = 90,(30 + 20) = 50 和 20。

text
| Id | Month | Salary |
|----|-------|--------|
| 1  | 3     | 90     |
| 1  | 2     | 50     |
| 1  | 1     | 20     |

员工 '2' 除去最近的一个月(月份 '2')的话,只有月份 '1' 这一个月的薪水记录。

text
| Id | Month | Salary |
|----|-------|--------|
| 2  | 1     | 20     |

员工 '3' 除去最近一个月(月份 '4')后有两个月,分别为:月份 '3' 薪水为 60 和 月份 '2' 薪水为 40。所以各月的累计情况如下:

text
| Id | Month | Salary |
|----|-------|--------|
| 3  | 3     | 100    |
| 3  | 2     | 40     |

sum()窗口大小,rank获取最近的一个月where来过滤,使用where联合查询来过滤也可

sql
SELECT Id, Month, Salary
FROM (SELECT Id, Month, SUM(Salary) OVER (PARTITION BY Id ORDER BY Month ROWS 2 PRECEDING) AS Salary, rank() OVER (PARTITION BY Id ORDER BY Month DESC) AS r
      FROM Employee) t
WHERE r > 1
ORDER BY Id, Month DESC;

lag函数的使用

sql
SELECT ID, MONTH, SALARY + IFNULL(L1, 0) + IFNULL(L2, 0) AS SALARY
FROM (SELECT *, LAG(SALARY, 1) OVER(PARTITION BY ID ORDER BY MONTH) AS L1, LAG(SALARY, 2) OVER(PARTITION BY ID ORDER BY MONTH) AS L2, RANK() OVER(PARTITION BY ID ORDER BY MONTH DESC) AS `RANK`
      FROM EMPLOYEE) AS A
WHERE `RANK` > 1
ORDER BY 1, 2 DESC;

自连接的使用

sql
SELECT
  a.Id AS id, a.Month AS month,SUM(b.Salary) AS Salary
FROM
  Employee a, Employee b
WHERE a.Id = b.Id 
AND a.Month >= b.Month
AND a.Month < b.Month+3
AND (a.Id, a.Month) NOT IN (SELECT Id, MAX(Month) FROM Employee GROUP BY Id)
GROUP BY a.Id, a.Month
ORDER BY a.Id, a.Month DESC

174.不同分组

写一个查询语句,将 2016 年 (TIV_2016) 所有成功投资的金额加起来,保留 2 位小数。

对于一个投保人,他在 2016 年成功投资的条件是:

他在 2015 年的投保额 (TIV_2015) 至少跟一个其他投保人在 2015 年的投保额相同。
他所在的城市必须与其他投保人都不同(也就是说维度和经度不能跟其他任何一个投保人完全相同)。
输入格式:
表 insurance 格式如下:

text
| Column Name | Type          |
|-------------|---------------|
| PID         | INTEGER(11)   |
| TIV_2015    | NUMERIC(15,2) |
| TIV_2016    | NUMERIC(15,2) |
| LAT         | NUMERIC(5,2)  |
| LON         | NUMERIC(5,2)  |

PID 字段是投保人的投保编号, TIV_2015 是该投保人在2015年的总投保金额, TIV_2016 是该投保人在2016年的投保金额, LAT 是投保人所在城市的维度, LON 是投保人所在城市的经度。

样例输入

text
| PID | TIV_2015 | TIV_2016 | LAT | LON |
|-----|----------|----------|-----|-----|
| 1   | 10       | 5        | 10  | 10  |
| 2   | 20       | 20       | 20  | 20  |
| 3   | 10       | 30       | 20  | 20  |
| 4   | 10       | 40       | 40  | 40  |

样例输出

text
| TIV_2016 |
|----------|
| 45.00    |

解释

就如最后一个投保人,第一个投保人同时满足两个条件:

  1. 他在 2015 年的投保金额 TIV_2015 为 '10' ,与第三个和第四个投保人在 2015 年的投保金额相同。
  2. 他所在城市的经纬度是独一无二的。
    第二个投保人两个条件都不满足。他在 2015 年的投资 TIV_2015 与其他任何投保人都不相同。
    且他所在城市的经纬度与第三个投保人相同。基于同样的原因,第三个投保人投资失败。
    所以返回的结果是第一个投保人和最后一个投保人的 TIV_2016 之和,结果是 45 。

不同分组,使用子查询,可能用到的函数concat()

sql
select
round(sum(TIV_2016),2)  TIV_2016
from 
(
select
TIV_2016,
count(TIV_2015) over(partition by TIV_2015 ) as rn,
count(TIV_2015) over(partition by LAT,LON) as rn_1
from 
insurance 
) t1 
where rn >1 and rn_1 =1

比较清晰的思路对需要的条件进行子查询

sql
select 
round(sum(TIV_2016) , 2) as TIV_2016
from 
insurance
where TIV_2015 in 
(
select 
TIV_2015
from
insurance
group by TIV_2015
having count(TIV_2015) >1
)
and concat(lat, lon) in
(
select
concat(lat, lon)
from
insurance
group by lat , lon
having count(*) = 1
)

175.偏移量函数

表:Stadium

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| visit_date    | date    |
| people        | int     |
+---------------+---------+

visit_date 是表的主键
每日人流量信息被记录在这三列信息中:序号 (id)、日期 (visit_date)、 人流量 (people)
每天只有一行记录,日期随着 id 的增加而增加
 

编写一个 SQL 查询以找出每行的人数大于或等于 100 且 id 连续的三行或更多行记录。

返回按 visit_date 升序排列的结果表。

查询结果格式如下所示。

Stadium table:

text
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
| 1    | 2017-01-01 | 10        |
| 2    | 2017-01-02 | 109       |
| 3    | 2017-01-03 | 150       |
| 4    | 2017-01-04 | 99        |
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-09 | 188       |
+------+------------+-----------+

Result table:

text
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-09 | 188       |
+------+------------+-----------+

id 为 5、6、7、8 的四行 id 连续,并且每行都有 >= 100 的人数记录。
请注意,即使第 7 行和第 8 行的 visit_date 不是连续的,输出也应当包含第 8 行,因为我们只需要考虑 id 连续的记录。
不输出 id 为 2 和 3 的行,因为至少需要三条 id 连续的记录。

sql
--分类讨论
select distinct a.* from stadium a,stadium b,stadium c
where a.people>=100 and b.people>=100 and c.people>=100
and (
     (a.id = b.id-1 and b.id = c.id -1) or
     (a.id = b.id-1 and a.id = c.id +1) or
     (a.id = b.id+1 and b.id = c.id +1)
) order by a.id
sql
select distinct t2.*    
from(
    select *, 
    lead(people,1)over(order by visit_date  ) as p2,
    lead(people,2)over(order by visit_date ) as p3
    from Stadium 
)t, Stadium t2
where t.people >=100 and p2>=100 and p3>=100 and 
t2.id>=t.id and t2.id-2<=t.id
sql
select id,visit_date,people from
(select id,visit_date,people,count(*)over(partition by k1) k2  录数
from 
(select id,visit_date,people,id-row_number()over(order by visit_date) k1 from stadium 
where people>=100
) a    
) b
where k2>=3

窗口大小那题也可以使用偏移量函数来实现
这一题也可以使用偏移量函数来实现

几个朋友来到电影院的售票处,准备预约连续空余座位。

你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?

text
| seat_id | free |
|---------|------|
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |

对于如上样例,你的查询语句应该返回如下结果。

text
| seat_id |
|---------|
| 3       |
| 4       |
| 5       |

注意:

seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。
连续空余座位的定义是大于等于 2 个连续空余的座位。

sql
select 
seat_id
from 
(
select
seat_id,free,
lag(free,1,0) over(order by seat_id) as pre,
lead(free,1,0) over(order by seat_id) as nex
from
cinema
)t
where free =1 and  (pre =1 or nex =1)
order by seat_id
sql
with sub as (
    select seat_id,seat_id - rank() over(order by seat_id) as rk from cinema
    where free = 1
)
select seat_id
from sub
where rk in (select rk from sub group by rk having count(1) > 1)
sql
select distinct(c1.seat_id) 
from cinema c1 join cinema c2
on    abs(c2.seat_id-c1.seat_id)=1
where c1.free=1 and c2.free=1
order by c1.seat_id

176.union all的用法

在 Facebook 或者 Twitter 这样的社交应用中,人们经常会发好友申请也会收到其他人的好友申请。

 

表 request_accepted 存储了所有好友申请通过的数据记录,其中, requester_id 和 accepter_id 都是用户的编号。

text
| requester_id | accepter_id | accept_date|
|--------------|-------------|------------|
| 1            | 2           | 2016_06-03 |
| 1            | 3           | 2016-06-08 |
| 2            | 3           | 2016-06-08 |
| 3            | 4           | 2016-06-09 |

写一个查询语句,求出谁拥有最多的好友和他拥有的好友数目。对于上面的样例数据,结果为:

text
| id | num |
|----|-----|
| 3  | 3   |

注意:

保证拥有最多好友数目的只有 1 个人。
好友申请只会被接受一次,所以不会有 requester_id 和 accepter_id 值都相同的重复记录。
 

解释:

编号为 '3' 的人是编号为 '1','2' 和 '4' 的好友,所以他总共有 3 个好友,比其他人都多。

sql
-- 使用union all 连接
select id, count(*) num
from 
    (select requester_id id from request_accepted 
    union all
    select accepter_id id from request_accepted) tmp 
group by id
order by count(*) desc
limit 1;
sql
select
id,nu as num
from
(
select
id,sum(num) as nu,
row_number() over(order by sum(num) desc) as rn
from
(
select requester_id as id, count(1) as num from request_accepted group by requester_id
union all
select  accepter_id as id1, count(1) as num1 from request_accepted group by accepter_id
) t1
group by id
) t2
where rn =1

177.sum(),count() 与if结合的注意事项

描述

给定 3 个表: salesperson, company, orders。
输出所有表 salesperson 中,没有向公司 'RED' 销售任何东西的销售员。

示例:
输入

表: salesperson

text
+----------+------+--------+-----------------+-----------+
| sales_id | name | salary | commission_rate | hire_date |
+----------+------+--------+-----------------+-----------+
|   1      | John | 100000 |     6           | 4/1/2006  |
|   2      | Amy  | 120000 |     5           | 5/1/2010  |
|   3      | Mark | 65000  |     12          | 12/25/2008|
|   4      | Pam  | 25000  |     25          | 1/1/2005  |
|   5      | Alex | 50000  |     10          | 2/3/2007  |
+----------+------+--------+-----------------+-----------+

表 salesperson 存储了所有销售员的信息。每个销售员都有一个销售员编号 sales_id 和他的名字 name 。

表: company

text
+---------+--------+------------+
| com_id  |  name  |    city    |
+---------+--------+------------+
|   1     |  RED   |   Boston   |
|   2     | ORANGE |   New York |
|   3     | YELLOW |   Boston   |
|   4     | GREEN  |   Austin   |
+---------+--------+------------+

表 company 存储了所有公司的信息。每个公司都有一个公司编号 com_id 和它的名字 name 。

表: orders

text
+----------+------------+---------+----------+--------+
| order_id | order_date | com_id  | sales_id | amount |
+----------+------------+---------+----------+--------+
| 1        |   1/1/2014 |    3    |    4     | 100000 |
| 2        |   2/1/2014 |    4    |    5     | 5000   |
| 3        |   3/1/2014 |    1    |    1     | 50000  |
| 4        |   4/1/2014 |    1    |    4     | 25000  |
+----------+----------+---------+----------+--------+

表 orders 存储了所有的销售数据,包括销售员编号 sales_id 和公司编号 com_id 。

输出

text
+------+
| name | 
+------+
| Amy  | 
| Mark | 
| Alex |
+------+

解释

根据表 orders 中的订单 '3' 和 '4' ,容易看出只有 'John' 和 'Pam' 两个销售员曾经向公司 'RED' 销售过。

所以我们需要输出表 salesperson 中所有其他人的名字。

sql
select 
name 
from 
salesperson
where sales_id  not in 
(
select
sales_id
from
company
join orders
on company.com_id = orders.com_id
where company.name = "RED"
)
sql
select 
name 
from 
salesperson
where sales_id  not in 
(
select
sales_id
from
company
join orders
on company.com_id = orders.com_id
where company.name = "RED"
)

另一个重要的知识点:辨析left join 中条件过滤 on和where的区别,这个注意事项和!=null重要

178.窗口不同分组

给如下两个表,写一个查询语句,求出在每一个工资发放日,每个部门的平均工资与公司的平均工资的比较结果 (高 / 低 / 相同)。

 

表: salary

text
| id | employee_id | amount | pay_date   |
|----|-------------|--------|------------|
| 1  | 1           | 9000   | 2017-03-31 |
| 2  | 2           | 6000   | 2017-03-31 |
| 3  | 3           | 10000  | 2017-03-31 |
| 4  | 1           | 7000   | 2017-02-28 |
| 5  | 2           | 6000   | 2017-02-28 |
| 6  | 3           | 8000   | 2017-02-28 |

employee_id 字段是表 employee 中 employee_id 字段的外键。

text
| employee_id | department_id |
|-------------|---------------|
| 1           | 1             |
| 2           | 2             |
| 3           | 2             |

对于如上样例数据,结果为:

text
| pay_month | department_id | comparison  |
|-----------|---------------|-------------|
| 2017-03   | 1             | higher      |
| 2017-03   | 2             | lower       |
| 2017-02   | 1             | same        |
| 2017-02   | 2             | same        |
sql
select
    pay_month,
    department_id,
    case
        when dept_avg > com_avg then 'higher'
        when dept_avg < com_avg then 'lower'
        else 'same'
    end comparison
from (
    select
        distinct
        pay_month,
        department_id,
        avg(amount) over(partition by pay_month) com_avg,
        avg(amount) over(partition by pay_month, department_id) dept_avg
    from (
        select
            date_format(s.pay_date, '%Y-%m') pay_month,
            e.department_id,
            s.amount
        from salary s 
        left join employee e on s.employee_id = e.employee_id
    ) t
) t1

方法二:分别求公司和部门的join比较

sql
select a.pay_month,b.department_id,
    case when b.d_avg_salarly>a.enter_avg_salary then 'higher' 
        when b.d_avg_salarly=a.enter_avg_salary then 'same'
        else 'lower' end as comparison  
from(
select date_format(pay_date,'%Y-%m') as pay_month ,avg(amount) as enter_avg_salary
from salary
group by date_format(pay_date,'%Y-%m')
) a
join 
( 
select date_format(s.pay_date,'%Y-%m') as pay_month 
        ,e.department_id
        ,avg(s.amount) as d_avg_salarly
from salary s
join employee e on s.employee_id = e.employee_id 
group by date_format(s.pay_date,'%Y-%m'),e.department_id ) b 
on a.pay_month = b.pay_month

179.行转列(序列函数实现)

一所美国大学有来自亚洲、欧洲和美洲的学生,他们的地理信息存放在如下 student 表中。

text
| name   | continent |
|--------|-----------|
| Jack   | America   |
| Pascal | Europe    |
| Xi     | Asia      |
| Jane   | America   |

写一个查询语句实现对大洲(continent)列的 透视表 操作,使得每个学生按照姓名的字母顺序依次排列在对应的大洲下面。输出的标题应依次为美洲(America)、亚洲(Asia)和欧洲(Europe)。

 

对于样例输入,它的对应输出是:

text
| America | Asia | Europe |
|---------|------|--------|
| Jack    | Xi   | Pascal |
| Jane    |      |        |

进阶:如果不能确定哪个大洲的学生数最多,你可以写出一个查询去生成上述学生报告吗?

sql
--分组相同州的不会出现在同一个分组中
select
     max(case when continent='America' then name else null end) as America
    ,max(case when continent='Asia' then name else null end) as Asia
    ,max(case when continent='Europe' then name else null end) as Europe
from(
    select row_number() over(partition by continent order by name) as rn,name,continent from student
) t
group by rn
order by rn 

注意事项:leedcode经常有人提...group by 之后必须用聚合函数,不用的话会返回第一个

sql
select America,Asia,Europe 
from(
    select row_number() over(order by name) as rn,name as America from student
    where continent='America'
) a
left join(
    select row_number() over(order by name) as rn,name as Asia from student
    where continent='Asia'
) b on a.rn=b.rn
left join(
    select row_number() over(order by name) as rn,name as Europe from student
    where continent='Europe'
) c on a.rn=c.rn

180.位运算

某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

 

例如,下表 cinema:

text
+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   1     | War       |   great 3D   |   8.9     |
|   2     | Science   |   fiction    |   8.5     |
|   3     | irish     |   boring     |   6.2     |
|   4     | Ice song  |   Fantacy    |   8.6     |
|   5     | House card|   Interesting|   9.1     |
+---------+-----------+--------------+-----------+

对于上面的例子,则正确的输出是为:

text
+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
+---------+-----------+--------------+-----------+
sql
奇数&1 就是1
SELECT
	id,
	movie,
	description,
	rating
FROM
	cinema
WHERE
	id & 1
AND description <> 'boring'
ORDER BY
	rating DESC

练习题 18:Summary-of-knowledge(2)

181.多条件查找having 与where联合字段☆

Table: Product

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
| unit_price   | int     |
+--------------+---------+

product_id 是这张表的主键
Table: Sales

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| seller_id   | int     |
| product_id  | int     |
| buyer_id    | int     |
| sale_date   | date    |
| quantity    | int     |
| price       | int     |
+------ ------+---------+

这个表没有主键,它可以有重复的行.
product_id 是 Product 表的外键.
编写一个 SQL 查询,查询购买了 S8 手机却没有购买 iPhone 的买家。注意这里 S8 和 iPhone 是 Product 表中的产品。

查询结果格式如下图表示:

Product table:

text
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1          | S8           | 1000       |
| 2          | G4           | 800        |
| 3          | iPhone       | 1400       |
+------------+--------------+------------+

Sales table:

text
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date  | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 1         | 1          | 1        | 2019-01-21 | 2        | 2000  |
| 1         | 2          | 2        | 2019-02-17 | 1        | 800   |
| 2         | 1          | 3        | 2019-06-02 | 1        | 800   |
| 3         | 3          | 3        | 2019-05-13 | 2        | 2800  |
+-----------+------------+----------+------------+----------+-------+

Result table:

text
+-------------+
| buyer_id    |
+-------------+
| 1           |
+-------------+

id 为 1 的买家购买了一部 S8,但是却没有购买 iPhone,而 id 为 3 的买家却同时购买了这 2 部手机。

这是错误的写法.....我又写错啦....标注一下

sql
select
buyer_id 
from
Sales
where
product_id in (select product_id from Product where product_name ="S8" )  
and 
product_id  in (select product_id from Product where product_name !="iPhone" ) 
group by buyer_id 

要写应该这样,这个叫粒度的问题...

sql
select distinct buyer_id
from Sales
where buyer_id not in (
    select buyer_id
    from Product p,Sales s
    where p.product_id = s.product_id
    and p.product_name = 'iPhone'
) 
and buyer_id in (
    select buyer_id
    from Product p,Sales s
    where p.product_id = s.product_id
    and p.product_name = 'S8'
)

最佳方法

sql
select
buyer_id
from 
Sales t1
join Product t2
on t1.product_id = t2.product_id
group by buyer_id
having sum(product_name = 'S8') >0 and sum(product_name = 'iPhone') =0

还有注意where联合字段子查询来过滤条件,题目是leedcode产品销售分析3

sql
-- where联合字段与子查询
SELECT PRODUCT_ID, YEAR AS FIRST_YEAR, QUANTITY, PRICE
FROM SALES
WHERE (PRODUCT_ID, YEAR) IN (SELECT PRODUCT_ID, MIN(YEAR)
                             FROM SALES
                             GROUP BY 1);

182.指标问题

Activity 活动记录表

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+

(player_id,event_date)是此表的主键
这张表显示了某些游戏的玩家的活动情况
每一行表示一个玩家的记录,在某一天使用某个设备注销之前,登录并玩了很多游戏(可能是 0)
 

玩家的 安装日期 定义为该玩家的第一个登录日。

玩家的 第一天留存率 定义为:假定安装日期为 X 的玩家的数量为 N ,其中在 X 之后的某一天重新登录的玩家数量为 M ,M/N 就是第一天留存率,四舍五入到小数点后两位。

编写一个 SQL 查询,报告所有安装日期、当天安装游戏的玩家数量和玩家的第一天留存率。

 

查询结果格式如下所示:

Activity 表:

text
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-03-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-01 | 0            |
| 3         | 4         | 2016-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result 表:

text
+------------+----------+----------------+
| install_dt | installs | Day1_retention |
+------------+----------+----------------+
| 2016-03-01 | 2        | 0.50           |
| 2017-06-25 | 1        | 0.00           |
+------------+----------+----------------+

玩家 1 和 3 在 2016-03-01 安装了游戏,但只有玩家 1 在 2016-03-02 重新登录,所以 2016-03-01 的第一天留存率是 1/2=0.50
玩家 2 在 2017-06-25 安装了游戏,但在 2017-06-26 没有重新登录,因此 2017-06-25 的第一天留存率为 0/1=0.00

sql
select a1.install_dt,
       count(*) installs,
       round(count(a2.event_date)/count(*),2) Day1_retention
from(
    select player_id,min(event_date) install_dt
    from Activity
    group by player_id
) a1
left join Activity a2
    on a1.player_id = a2.player_id and datediff(a2.event_date,a1.install_dt)=1
group by a1.install_dt

--注意min/max窗口在求指标时的使用
下面的思路就是先获取每个用户第一次登陆的时间,然后与原始表进行比较时间是否存在时间+1的情况

sql
select first_date as install_dt,
count(distinct player_id) as installs,
round(sum(if(datediff(event_date,first_date)=1,1,0))/count(distinct player_id),2)
as Day1_retention
from
(
    select player_id,event_date,min(event_date) over(partition by player_id) as first_date
    from activity
)tmp
group by first_date

Table: Activity

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+

(player_id,event_date)是此表的主键。
这张表显示了某些游戏的玩家的活动情况。
每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0)。
 

编写一个 SQL 查询,报告在首次登录的第二天再次登录的玩家的比率,四舍五入到小数点后两位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。

查询结果格式如下所示:

Activity table:

text
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-03-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result table:

text
+-----------+
| fraction  |
+-----------+
| 0.33      |
+-----------+

只有 ID 为 1 的玩家在第一天登录后才重新登录,所以答案是 1/3 = 0.33

sql
select 
round((count(b.player_id) / count(a.player_id) ),2) as   fraction 
from 
(
select 
player_id,min(event_date) as event_date
from
Activity
group by player_id
) a 
left join Activity b 
on a.player_id = b.player_id and datediff(b.event_date,a.event_date) =1
sql
select
round(sum(if(datediff(event_date,rn)=1,1,0)) /  count(distinct player_id) ,2)  fraction
from 
(
select
player_id,event_date,min(event_date) over(partition by player_id) rn
from 
Activity 
) t1
sql
select
round(sum(if(datediff(event_date,rn)=-1,1,0)) /  count(distinct player_id) ,2)  fraction 
from 
(
select
player_id,event_date,
lead(event_date) over(partition by player_id order by event_date asc) rn,
row_number() over(partition by player_id order by event_date) rn_1
from 
Activity
) t1
where rn_1 =1

183.构建辅助表

支出表: Spending

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| spend_date  | date    |
| platform    | enum    | 
| amount      | int     |
+-------------+---------+

这张表记录了用户在一个在线购物网站的支出历史,该在线购物平台同时拥有桌面端('desktop')和手机端('mobile')的应用程序。
这张表的主键是 (user_id, spend_date, platform)。
平台列 platform 是一种 ENUM ,类型为('desktop', 'mobile')。
 

写一段 SQL 来查找每天 仅 使用手机端用户、仅 使用桌面端用户和 同时 使用桌面端和手机端的用户人数和总支出金额。

查询结果格式如下例所示:

Spending table:

text
+---------+------------+----------+--------+
| user_id | spend_date | platform | amount |
+---------+------------+----------+--------+
| 1       | 2019-07-01 | mobile   | 100    |
| 1       | 2019-07-01 | desktop  | 100    |
| 2       | 2019-07-01 | mobile   | 100    |
| 2       | 2019-07-02 | mobile   | 100    |
| 3       | 2019-07-01 | desktop  | 100    |
| 3       | 2019-07-02 | desktop  | 100    |
+---------+------------+----------+--------+

Result table:

text
+------------+----------+--------------+-------------+
| spend_date | platform | total_amount | total_users |
+------------+----------+--------------+-------------+
| 2019-07-01 | desktop  | 100          | 1           |
| 2019-07-01 | mobile   | 100          | 1           |
| 2019-07-01 | both     | 200          | 1           |
| 2019-07-02 | desktop  | 100          | 1           |
| 2019-07-02 | mobile   | 100          | 1           |
| 2019-07-02 | both     | 0            | 0           |
+------------+----------+--------------+-------------+ 

在 2019-07-01, 用户1 同时 使用桌面端和手机端购买, 用户2 仅 使用了手机端购买,而用户3 仅 使用了桌面端购买
在 2019-07-02, 用户2 仅 使用了手机端购买, 用户3 仅 使用了桌面端购买,且没有用户 同时 使用桌面端和手机端购买

sql
-- 先按用户维度集合,打一个标签,然后对这个标签聚合
select 
t1.spend_date,t1.platform,
ifnull(sum(amount),0)  as total_amount,
ifnull(count(distinct user_id),0) as total_users
from
(
select distinct spend_date, "desktop" platform from Spending
union
select distinct spend_date, "mobile" platform from Spending
union
select distinct spend_date, "both" platform from Spending
) t1
left join
( 
select 
spend_date,user_id,
if(count(distinct platform) =1,platform,"both") as platform,
sum(amount) as amount
from
Spending
group by spend_date, user_id
) t2
on t1.spend_date = t2.spend_date and t1.platform = t2.platform
group by t1.spend_date,t1.platform

Product 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
+---------------+---------+

product_id 是这张表的主键。
product_name 是产品的名称。

Sales 表:

text
+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| product_id          | int     |
| period_start        | date    |
| period_end          | date    |
| average_daily_sales | int     |
+---------------------+---------+

product_id 是这张表的主键。
period_start 和 period_end 是该产品销售期的起始日期和结束日期,且这两个日期包含在销售期内。
average_daily_sales 列存储销售期内该产品的日平均销售额。

编写一段 SQL 查询每个产品每年的总销售额,并包含 product_id, product_name 以及 report_year 等信息。

销售年份的日期介于 2018 年到 2020 年之间。你返回的结果需要按 product_id 和 report_year 排序。

查询结果格式如下例所示:

Product table:

text
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 1          | LC Phone     |
| 2          | LC T-Shirt   |
| 3          | LC Keychain  |
+------------+--------------+

Sales table:

text
+------------+--------------+-------------+---------------------+
| product_id | period_start | period_end  | average_daily_sales |
+------------+--------------+-------------+---------------------+
| 1          | 2019-01-25   | 2019-02-28  | 100                 |
| 2          | 2018-12-01   | 2020-01-01  | 10                  |
| 3          | 2019-12-01   | 2020-01-31  | 1                   |
+------------+--------------+-------------+---------------------+

Result table:

text
+------------+--------------+-------------+--------------+
| product_id | product_name | report_year | total_amount |
+------------+--------------+-------------+--------------+
| 1          | LC Phone     |    2019     | 3500         |
| 2          | LC T-Shirt   |    2018     | 310          |
| 2          | LC T-Shirt   |    2019     | 3650         |
| 2          | LC T-Shirt   |    2020     | 10           |
| 3          | LC Keychain  |    2019     | 31           |
| 3          | LC Keychain  |    2020     | 31           |
+------------+--------------+-------------+--------------+

LC Phone 在 2019-01-25 至 2019-02-28 期间销售,该产品销售时间总计35天。销售总额 35100 = 3500。
LC T-shirt 在 2018-12-01 至 2020-01-01 期间销售,该产品在2018年、2019年、2020年的销售时间分别是31天、365天、1天,2018年、2019年、2020年的销售总额分别是31
10=310、36510=3650、110=10。
LC Keychain 在 2019-12-01 至 2020-01-31 期间销售,该产品在2019年、2020年的销售时间分别是:31天、31天,2019年、2020年的销售总额分别是311=31、311=31。

sql
SELECT
    CAST(p.product_id AS CHAR) product_id,
    p.product_name,
    report_year,
    (DATEDIFF(IF(end_dt>period_end,period_end,end_dt),IF(start_dt>period_start,start_dt,period_start)) + 1) * average_daily_sales total_amount
FROM
    Product p
CROSS JOIN
    (
    SELECT '2018' report_year,'2018-01-01' start_dt,'2018-12-31' end_dt
    UNION ALL
    SELECT '2019' report_year,'2019-01-01' start_dt,'2019-12-31' end_dt
    UNION ALL
    SELECT '2020' report_year,'2020-01-01' start_dt,'2020-12-31' end_dt
    ) y
INNER JOIN
    Sales s
ON p.product_id = s.product_id
WHERE
    period_start<=end_dt AND period_end>=start_dt
ORDER BY
    product_id,
    report_year

184.avg口径

动作表: Actions

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| post_id       | int     |
| action_date   | date    |
| action        | enum    |
| extra         | varchar |
+---------------+---------+

这张表没有主键,并有可能存在重复的行。
action 列的类型是 ENUM,可能的值为 ('view', 'like', 'reaction', 'comment', 'report', 'share')。
extra 列拥有一些可选信息,例如:报告理由(a reason for report)或反应类型(a type of reaction)等。
移除表: Removals

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| post_id       | int     |
| remove_date   | date    | 
+---------------+---------+

这张表的主键是 post_id。
这张表的每一行表示一个被移除的帖子,原因可能是由于被举报或被管理员审查。
 

编写一段 SQL 来查找:在被报告为垃圾广告的帖子中,被移除的帖子的每日平均占比,四舍五入到小数点后 2 位。

查询结果的格式如下:

Actions table:

text
+---------+---------+-------------+--------+--------+
| user_id | post_id | action_date | action | extra  |
+---------+---------+-------------+--------+--------+
| 1       | 1       | 2019-07-01  | view   | null   |
| 1       | 1       | 2019-07-01  | like   | null   |
| 1       | 1       | 2019-07-01  | share  | null   |
| 2       | 2       | 2019-07-04  | view   | null   |
| 2       | 2       | 2019-07-04  | report | spam   |
| 3       | 4       | 2019-07-04  | view   | null   |
| 3       | 4       | 2019-07-04  | report | spam   |
| 4       | 3       | 2019-07-02  | view   | null   |
| 4       | 3       | 2019-07-02  | report | spam   |
| 5       | 2       | 2019-07-03  | view   | null   |
| 5       | 2       | 2019-07-03  | report | racism |
| 5       | 5       | 2019-07-03  | view   | null   |
| 5       | 5       | 2019-07-03  | report | racism |
+---------+---------+-------------+--------+--------+

Removals table:

text
+---------+-------------+
| post_id | remove_date |
+---------+-------------+
| 2       | 2019-07-20  |
| 3       | 2019-07-18  |
+---------+-------------+

Result table:

text
+-----------------------+
| average_daily_percent |
+-----------------------+
| 75.00                 |
+-----------------------+

2019-07-04 的垃圾广告移除率是 50%,因为有两张帖子被报告为垃圾广告,但只有一个得到移除。
2019-07-02 的垃圾广告移除率是 100%,因为有一张帖子被举报为垃圾广告并得到移除。
其余几天没有收到垃圾广告的举报,因此平均值为:(50 + 100) / 2 = 75%
注意,输出仅需要一个平均值即可,我们并不关注移除操作的日期。

sql
select 
round(avg(s1),2)   as average_daily_percent
from 
(
select
action_date,
count(distinct Removals.post_id ) / count(distinct Actions.post_id) * 100 as s1
from
Actions 
left join 
Removals on Actions.post_id = Removals.post_id
where extra = "spam"
group by action_date
) t1

两种口径

sql
SELECT
    ROUND(COUNT(DISTINCT R.post_id) / COUNT(DISTINCT A.post_id) * 100,2) average_daily_percent
FROM 
    Actions A
LEFT JOIN
    Removals R
ON A.post_id = R.post_id
WHERE
    extra='spam'

185.tag标签

Transactions 记录表

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| id             | int     |
| country        | varchar |
| state          | enum    |
| amount         | int     |
| trans_date     | date    |
+----------------+---------+

id 是这个表的主键。
该表包含有关传入事务的信息。
状态列是类型为 [approved(已批准)、declined(已拒绝)] 的枚举。
 

Chargebacks 表

text
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| trans_id       | int     |
| charge_date    | date    |
+----------------+---------+

退单包含有关放置在事务表中的某些事务的传入退单的基本信息。
trans_id 是 transactions 表的 id 列的外键。
每项退单都对应于之前进行的交易,即使未经批准。
 

编写一个 SQL 查询,以查找每个月和每个国家/地区的已批准交易的数量及其总金额、退单的数量及其总金额。

注意:在您的查询中,给定月份和国家,忽略所有为零的行。

查询结果格式如下所示:

Transactions 表:

text
+------+---------+----------+--------+------------+
| id   | country | state    | amount | trans_date |
+------+---------+----------+--------+------------+
| 101  | US      | approved | 1000   | 2019-05-18 |
| 102  | US      | declined | 2000   | 2019-05-19 |
| 103  | US      | approved | 3000   | 2019-06-10 |
| 104  | US      | declined | 4000   | 2019-06-13 |
| 105  | US      | approved | 5000   | 2019-06-15 |
+------+---------+----------+--------+------------+

Chargebacks 表:

text
+------------+------------+
| trans_id   | trans_date |
+------------+------------+
| 102        | 2019-05-29 |
| 101        | 2019-06-30 |
| 105        | 2019-09-18 |
+------------+------------+

Result 表:

text
+----------+---------+----------------+-----------------+-------------------+--------------------+
| month    | country | approved_count | approved_amount | chargeback_count  | chargeback_amount  |
+----------+---------+----------------+-----------------+-------------------+--------------------+
| 2019-05  | US      | 1              | 1000            | 1                 | 2000               |
| 2019-06  | US      | 2              | 8000            | 1                 | 1000               |
| 2019-09  | US      | 0              | 0               | 1                 | 5000               |
+----------+---------+----------------+-----------------+-------------------+--------------------+

不是要统计另一张表的退单情况,打一个标签与原始表union all

sql
select
    date_format(trans_date, '%Y-%m') as month,
    country,
    sum(if(state = 'approved',1,0)) as approved_count,
    sum(if(state = 'approved',amount,0)) as approved_amount,
    sum(if(state = 'chargeback',1,0)) as chargeback_count,
    sum(if(state = 'chargeback',amount,0)) as chargeback_amount
from
    (select
        *
    from
        transactions
    union all
    select
        trans_id as id,
        country,
        'chargeback' as state,
        amount,
        c.trans_date
    from
        chargebacks c left join transactions t 
        on t.id = c.trans_id) as temp
group by 1,2
having approved_count <> 0 or chargeback_count <> 0

186.构造0-max

表: Visits

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| visit_date    | date    |
+---------------+---------+

(user_id, visit_date) 是该表的主键
该表的每行表示 user_id 在 visit_date 访问了银行
 

表: Transactions

text
+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| user_id          | int     |
| transaction_date | date    |
| amount           | int     |
+------------------+---------+

该表没有主键,所以可能有重复行
该表的每一行表示 user_id 在 transaction_date 完成了一笔 amount 数额的交易
可以保证用户 (user) 在 transaction_date 访问了银行 (也就是说 Visits 表包含 (user_id, transaction_date) 行)
 

银行想要得到银行客户在一次访问时的交易次数和相应的在一次访问时该交易次数的客户数量的图表

写一条 SQL 查询多少客户访问了银行但没有进行任何交易,多少客户访问了银行进行了一次交易等等

结果包含两列:

transactions_count: 客户在一次访问中的交易次数
visits_count: 在 transactions_count 交易次数下相应的一次访问时的客户数量
transactions_count 的值从 0 到所有用户一次访问中的 max(transactions_count) 

按 transactions_count 排序

下面是查询结果格式的例子:

Visits 表:

text
+---------+------------+
| user_id | visit_date |
+---------+------------+
| 1       | 2020-01-01 |
| 2       | 2020-01-02 |
| 12      | 2020-01-01 |
| 19      | 2020-01-03 |
| 1       | 2020-01-02 |
| 2       | 2020-01-03 |
| 1       | 2020-01-04 |
| 7       | 2020-01-11 |
| 9       | 2020-01-25 |
| 8       | 2020-01-28 |
+---------+------------+

Transactions 表:

text
+---------+------------------+--------+
| user_id | transaction_date | amount |
+---------+------------------+--------+
| 1       | 2020-01-02       | 120    |
| 2       | 2020-01-03       | 22     |
| 7       | 2020-01-11       | 232    |
| 1       | 2020-01-04       | 7      |
| 9       | 2020-01-25       | 33     |
| 9       | 2020-01-25       | 66     |
| 8       | 2020-01-28       | 1      |
| 9       | 2020-01-25       | 99     |
+---------+------------------+--------+

结果表:

text
+--------------------+--------------+
| transactions_count | visits_count |
+--------------------+--------------+
| 0                  | 4            |
| 1                  | 5            |
| 2                  | 0            |
| 3                  | 1            |
+--------------------+--------------+
  • 对于 transactions_count = 0, visits 中 (1, "2020-01-01"), (2, "2020-01-02"), (12, "2020-01-01") 和 (19, "2020-01-03") 没有进行交易,所以 visits_count = 4 。
  • 对于 transactions_count = 1, visits 中 (2, "2020-01-03"), (7, "2020-01-11"), (8, "2020-01-28"), (1, "2020-01-02") 和 (1, "2020-01-04") 进行了一次交易,所以 visits_count = 5 。
  • 对于 transactions_count = 2, 没有客户访问银行进行了两次交易,所以 visits_count = 0 。
  • 对于 transactions_count = 3, visits 中 (9, "2020-01-25") 进行了三次交易,所以 visits_count = 1 。
  • 对于 transactions_count >= 4, 没有客户访问银行进行了超过3次交易,所以我们停止在 transactions_count = 3 。

是一次不是第一次,两表连接,group by 用户和时间,获取时间维度下,用户每次交易次数,这个对交易次数group by,获取这个交易次数下游多少用户,所以这个报表是对时间sum的,这个是难题......以后再写一遍

sql
with temp1 as (
    select transactions_count,count(user_id) visits_count
    from (
        select v.user_id,count(t.user_id) transactions_count
        from Visits v
        left join Transactions t
        on v.user_id = t.user_id and v.visit_date = transaction_date
        group by v.user_id,v.visit_date
    ) a
    group by transactions_count
)

select temp2.transactions_count,ifnull(temp1.visits_count,0) visits_count
from (
    select 0 transactions_count
    union
    select row_number() over (order by transaction_date) transactions_count
    from Transactions
) temp2
left join temp1
on temp2.transactions_count = temp1.transactions_count
where temp2.transactions_count <= (
    select max(transactions_count)
    from temp1
)

187.等量代换

表 Variables:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| name          | varchar |
| value         | int     |
+---------------+---------+

name 是该表主键.
该表包含了存储的变量及其对应的值.

表 Expressions:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| left_operand  | varchar |
| operator      | enum    |
| right_operand | varchar |
+---------------+---------+

(left_operand, operator, right_operand) 是该表主键.
该表包含了需要计算的布尔表达式.
operator 是枚举类型, 取值于('<', '>', '=')
left_operand 和 right_operand 的值保证存在于 Variables 表单中.

写一个 SQL 查询, 以计算表 Expressions 中的布尔表达式.

返回的结果表没有顺序要求.

查询结果格式如下例所示.

Variables 表:

text
+------+-------+
| name | value |
+------+-------+
| x    | 66    |
| y    | 77    |
+------+-------+

Expressions 表:

text
+--------------+----------+---------------+
| left_operand | operator | right_operand |
+--------------+----------+---------------+
| x            | >        | y             |
| x            | <        | y             |
| x            | =        | y             |
| y            | >        | x             |
| y            | <        | x             |
| x            | =        | x             |
+--------------+----------+---------------+

Result 表:

text
+--------------+----------+---------------+-------+
| left_operand | operator | right_operand | value |
+--------------+----------+---------------+-------+
| x            | >        | y             | false |
| x            | <        | y             | true  |
| x            | =        | y             | false |
| y            | >        | x             | true  |
| y            | <        | x             | false |
| x            | =        | x             | true  |
+--------------+----------+---------------+-------+

如上所示, 你需要通过使用 Variables 表来找到 Expressions 表中的每一个布尔表达式的值

sql
select e.*,
    case
        when operator = '=' and v1.value = v2.value then 'true'
        when operator = '>' and v1.value > v2.value then 'true'
        when operator = '<' and v1.value < v2.value then 'true'
        else 'false'
    end value
from Expressions e
left join Variables v1
on e.left_operand = v1.name
left join Variables v2
on e.right_operand = v2.name

188.窗口函数关联

表: UserActivity

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| username      | varchar |
| activity      | varchar |
| startDate     | Date    |
| endDate       | Date    |
+---------------+---------+

该表不包含主键
该表包含每个用户在一段时间内进行的活动的信息
名为 username 的用户在 startDate 到 endDate 日内有一次活动

写一条SQL查询展示每一位用户 最近第二次 的活动

如果用户仅有一次活动,返回该活动

一个用户不能同时进行超过一项活动,以 任意 顺序返回结果

下面是查询结果格式的例子:

UserActivity 表:

text
+------------+--------------+-------------+-------------+
| username   | activity     | startDate   | endDate     |
+------------+--------------+-------------+-------------+
| Alice      | Travel       | 2020-02-12  | 2020-02-20  |
| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
| Alice      | Travel       | 2020-02-24  | 2020-02-28  |
| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+

Result 表:

text
+------------+--------------+-------------+-------------+
| username   | activity     | startDate   | endDate     |
+------------+--------------+-------------+-------------+
| Alice      | Dancing      | 2020-02-21  | 2020-02-23  |
| Bob        | Travel       | 2020-02-11  | 2020-02-18  |
+------------+--------------+-------------+-------------+

Alice 最近一次的活动是从 2020-02-24 到 2020-02-28 的旅行, 在此之前的 2020-02-21 到 2020-02-23 她进行了舞蹈
Bob 只有一条记录,我们就取这条记录

sql
--没想到,采用一个组内全局的count来获取
select username,activity,startDate,endDate
from(
    select *,
        row_number() over (partition by username order by startDate desc) r,
        count(*) over (partition by username) c
    from UserActivity
) a
where c = 1 or r = 2
sql
select
username, activity,to_char(startDate,'yyyy-mm-dd') startDate,to_char(endDate,'yyyy-mm-dd') endDate 
from 
(
select
username,activity,startDate,endDate,
row_number() over(partition by username order by startDate  ) as rn1  
from 
(
select
username,activity,startDate,endDate,
row_number() over(partition by username order by startDate desc ) as rn 
from
UserActivity ) t1 
where rn = 1 or rn = 2  ) t2
where rn1 = 1

189.在if中使用负数

Stocks 表:

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| stock_name    | varchar |
| operation     | enum    |
| operation_day | int     |
| price         | int     |
+---------------+---------+

(stock_name, day) 是这张表的主键
operation 列使用的是一种枚举类型,包括:('Sell','Buy')
此表的每一行代表了名为 stock_name 的某支股票在 operation_day 这一天的操作价格。
保证股票的每次'Sell'操作前,都有相应的'Buy'操作。

编写一个SQL查询来报告每支股票的资本损益。

股票的资本损益是一次或多次买卖股票后的全部收益或损失。

以任意顺序返回结果即可。

SQL查询结果的格式如下例所示:

Stocks 表:

text
+---------------+-----------+---------------+--------+
| stock_name    | operation | operation_day | price  |
+---------------+-----------+---------------+--------+
| Leetcode      | Buy       | 1             | 1000   |
| Corona Masks  | Buy       | 2             | 10     |
| Leetcode      | Sell      | 5             | 9000   |
| Handbags      | Buy       | 17            | 30000  |
| Corona Masks  | Sell      | 3             | 1010   |
| Corona Masks  | Buy       | 4             | 1000   |
| Corona Masks  | Sell      | 5             | 500    |
| Corona Masks  | Buy       | 6             | 1000   |
| Handbags      | Sell      | 29            | 7000   |
| Corona Masks  | Sell      | 10            | 10000  |
+---------------+-----------+---------------+--------+

Result 表:

text
+---------------+-------------------+
| stock_name    | capital_gain_loss |
+---------------+-------------------+
| Corona Masks  | 9500              |
| Leetcode      | 8000              |
| Handbags      | -23000            |
+---------------+-------------------+

Leetcode 股票在第一天以1000美元的价格买入,在第五天以9000美元的价格卖出。资本收益=9000-1000=8000美元。
Handbags 股票在第17天以30000美元的价格买入,在第29天以7000美元的价格卖出。资本损失=7000-30000=-23000美元。
Corona Masks 股票在第1天以10美元的价格买入,在第3天以1010美元的价格卖出。在第4天以1000美元的价格再次购买,在第5天以500美元的价格出售。最后,它在第6天以1000美元的价格被买走,在第10天以10000美元的价格被卖掉。资本损益是每次(’Buy'->'Sell')操作资本收益或损失的和=(1010-10)+(500-1000)+(10000-1000)=1000-500+9000=9500美元。

sql
--简单题
select
stock_name,
sum(if(operation = "Buy",-price,price)) capital_gain_loss
from
Stocks
group by  stock_name
sql
--这题是指标分析那题
create table  TEST(
     DEP_CODE varchar(10),
     ITEM_CODE varchar(10),
     ITEM_VALUE int
);
insert into TEST values ('单位一','A',100);
insert into TEST values ('单位二','A',200);
insert into TEST values ('单位一','B',300);
insert into TEST values ('单位二','B',300);
insert into TEST values ('单位一','C',350);
insert into TEST values ('单位二','C',300);

select
    DEP_CODE,
    ITEM_CODE,
    ITEM_VALUE
from
    TEST
UNION ALL

select
    DEP_CODE,
    'D'  as ITEM_CODE,
    sum(if(ITEM_CODE = 'C',-ITEM_VALUE,ITEM_VALUE)) as  ITEM_VALUE
from
    TEST
group by  DEP_CODE

190.循环

sql
Table: Tasks

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| task_id        | int     |
| subtasks_count | int     |
+----------------+---------+
task_id is the primary key for this table.
Each row in this table indicates that task_id was divided into subtasks_count subtasks labelled from 1 to subtasks_count.
It is guaranteed that 2 <= subtasks_count <= 20.
Table: Executed

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| task_id       | int     |
| subtask_id    | int     |
+---------------+---------+
(task_id, subtask_id) is the primary key for this table.
Each row in this table indicates that for the task task_id, the subtask with ID subtask_id was executed successfully.
It is guaranteed that subtask_id <= subtasks_count for each task_id.
Write an SQL query to report the IDs of the missing subtasks for each task_id.

Return the result table in any order.

The query result format is in the following example:

Tasks table:
+---------+----------------+
| task_id | subtasks_count |
+---------+----------------+
| 1       | 3              |
| 2       | 2              |
| 3       | 4              |
+---------+----------------+

Executed table:
+---------+------------+
| task_id | subtask_id |
+---------+------------+
| 1       | 2          |
| 3       | 1          |
| 3       | 2          |
| 3       | 3          |
| 3       | 4          |
+---------+------------+

Result table:
+---------+------------+
| task_id | subtask_id |
+---------+------------+
| 1       | 1          |
| 1       | 3          |
| 2       | 1          |
| 2       | 2          |
+---------+------------+
Task 1 was divided into 3 subtasks (1, 2, 3). Only subtask 2 was excuted successfully, so we include (1, 1) and (1, 3) in the answer.
Task 2 was divided into 2 subtasks (1, 2). No subtask was excuted successfully, so we include (2, 1) and (2, 2) in the answer.
Task 3 was divided into 4 subtasks (1, 2, 3, 4). All of the subtasks were excuted succes.
sql
WITH RECURSIVE t(task_id, subtask_id) AS
(
    select distinct task_id, 1 from tasks
    UNION ALL
    SELECT t.task_id, subtask_id + 1 from t join tasks on t.task_id = tasks.task_id where subtask_id < subtasks_count
)
select
task_id, subtask_id 
from 
t 
where (task_id, subtask_id) not in (select task_id, subtask_id from Executed )

表: Drivers

text
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| driver_id   | int     |
| join_date   | date    |
+-------------+---------+

driver_id是该表的主键。
该表的每一行均包含驾驶员的ID以及他们加入Hopper公司的日期。
 

表: Rides

text
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| ride_id      | int     |
| user_id      | int     |
| requested_at | date    |
+--------------+---------+

ride_id是该表的主键。
该表的每一行均包含行程ID(ride_id),用户ID(user_id)以及该行程的日期(requested_at)。
该表中可能有一些不被接受的乘车请求。
 

表: AcceptedRides

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| ride_id       | int     |
| driver_id     | int     |
| ride_distance | int     |
| ride_duration | int     |
+---------------+---------+

ride_id是该表的主键。
该表的每一行都包含已接受的行程信息。
表中的行程信息都在“Rides”表中存在。
 

编写SQL查询以报告2020年每个月的以下统计信息:

截至某月底,当前在Hopper公司工作的驾驶员数量(active_drivers)。
该月接受的乘车次数(accepted_rides)。
返回按month 升序排列的结果表,其中month 是月份的数字(一月是1,二月是2,依此类推)。

查询结果格式如下例所示。

表 Drivers:

text
+-----------+------------+
| driver_id | join_date  |
+-----------+------------+
| 10        | 2019-12-10 |
| 8         | 2020-1-13  |
| 5         | 2020-2-16  |
| 7         | 2020-3-8   |
| 4         | 2020-5-17  |
| 1         | 2020-10-24 |
| 6         | 2021-1-5   |
+-----------+------------+

表 Rides:

text
+---------+---------+--------------+
| ride_id | user_id | requested_at |
+---------+---------+--------------+
| 6       | 75      | 2019-12-9    |
| 1       | 54      | 2020-2-9     |
| 10      | 63      | 2020-3-4     |
| 19      | 39      | 2020-4-6     |
| 3       | 41      | 2020-6-3     |
| 13      | 52      | 2020-6-22    |
| 7       | 69      | 2020-7-16    |
| 17      | 70      | 2020-8-25    |
| 20      | 81      | 2020-11-2    |
| 5       | 57      | 2020-11-9    |
| 2       | 42      | 2020-12-9    |
| 11      | 68      | 2021-1-11    |
| 15      | 32      | 2021-1-17    |
| 12      | 11      | 2021-1-19    |
| 14      | 18      | 2021-1-27    |
+---------+---------+--------------+

表 AcceptedRides:

text
+---------+-----------+---------------+---------------+
| ride_id | driver_id | ride_distance | ride_duration |
+---------+-----------+---------------+---------------+
| 10      | 10        | 63            | 38            |
| 13      | 10        | 73            | 96            |
| 7       | 8         | 100           | 28            |
| 17      | 7         | 119           | 68            |
| 20      | 1         | 121           | 92            |
| 5       | 7         | 42            | 101           |
| 2       | 4         | 6             | 38            |
| 11      | 8         | 37            | 43            |
| 15      | 8         | 108           | 82            |
| 12      | 8         | 38            | 34            |
| 14      | 1         | 90            | 74            |
+---------+-----------+---------------+---------------+

结果表:

text
+-------+----------------+----------------+
| month | active_drivers | accepted_rides |
+-------+----------------+----------------+
| 1     | 2              | 0              |
| 2     | 3              | 0              |
| 3     | 4              | 1              |
| 4     | 4              | 0              |
| 5     | 5              | 0              |
| 6     | 5              | 1              |
| 7     | 5              | 1              |
| 8     | 5              | 1              |
| 9     | 5              | 0              |
| 10    | 6              | 0              |
| 11    | 6              | 2              |
| 12    | 6              | 1              |
+-------+----------------+----------------+

截至1月底->两个活跃的驾驶员(10,8),没有被接受的行程。
截至2月底->三个活跃的驾驶员(10,8,5),没有被接受的行程。
截至3月底->四个活跃的驾驶员(10,8,5,7),一个被接受的行程(10)。
截至4月底->四个活跃的驾驶员(10,8,5,7),没有被接受的行程。
截至5月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
截至6月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(13)。
截至7月底->五个活跃的驾驶员(10,8,5,7,4),一个被接受的行程(7)。
截至8月底->五个活跃的驾驶员(10,8,5,7,4),一位接受的行程(17)。
截至9月底->五个活跃的驾驶员(10,8,5,7,4),没有被接受的行程。
截至10月底->六个活跃的驾驶员(10,8,5,7,4,1),没有被接受的行程。
截至11月底->六个活跃的驾驶员(10,8,5,7,4,1),两个被接受的行程(20,5)。
截至12月底->六个活跃的驾驶员(10,8,5,7,4,1),一个被接受的行程(2)。

sql
--我又写麻烦了.直接使用year和month即可
with recursive mon_time as 
(
    select 1 as month
    union all 
    select month + 1 from mon_time where month <= 11
)

select m.month,
sum(ifnull(d.num_driver,0)) over(order by m.month) as active_drivers,
ifnull(num_rides,0) as accepted_rides

from mon_time m 
left join 
(
    select if(year(join_date)<'2020',1,month(join_date)) as month_driver,
    count(driver_id) as num_driver
    from drivers
    where year(join_date)<='2020'
    group by if(year(join_date)<'2020',1,month(join_date))
)d  on m.month = month_driver
left join
(
    select month(requested_at) as month_rides,
    count(ride_id) as num_rides
    from rides 
    where ride_id in (select ride_id from acceptedrides)
    and year(requested_at) = '2020'
    group by month(requested_at)
)r on m.month = month_rides
group by m.month
order by m.month

表: Customers

text
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
+---------------+---------+

customer_id 是该表主键.
该表第一行包含了顾客的名字和id.

写一个 SQL 语句, 找到所有遗失的顾客id. 遗失的顾客id是指那些不在 Customers 表中, 值却处于 1 和表中最大 customer_id 之间的id.

注意: 最大的 customer_id 值不会超过 100.

返回结果按 ids 升序排列

查询结果格式如下例所示.

Customers 表:

text
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1           | Alice         |
| 4           | Bob           |
| 5           | Charlie       |
+-------------+---------------+

Result 表:

text
+-----+
| ids |
+-----+
| 2   |
| 3   |
+-----+

表中最大的customer_id是5, 所以在范围[1,5]内, ID2和3从表中遗失.

sql
with recursive x as (
select 1 as n 
union all 
select n + 1 from  x where n <100
)

select
n as ids  
from 
x
where  n <= (select max(customer_id) from customers) and n not in (select customer_id from customers)

还有一些用法,找不到题目来说明了
1.join时 使用or来代替union all
2.left join 同一张表join来避免子查询
3.采用一个组内全局的count来获取,top问题
4.联合去重distinct
5.窗口大小 窗口函数结合使用的使用技巧题
6.窗口order by排序字段为count等聚合函数
7.SQL中的正则用法,SQL中的文本处理函数
.....

练习题 19:互联网SQL50题再写一遍

很多地方都有这些题目,这些题目1年前也写过一遍,这里回顾一下,使SQL练习这个主题成为一个完整的主题,这些题目也会较好的巩固子查询/where联合查询/group by维度/自连接 等基本的用法,再写一遍希望有所收获

花了一个早上,和一年前对比一下,以前写还是有点吃力,现在写发现,哈哈哈,都是简单题,但还是发现如下问题:
1.对自连接的处理还是不够好,理解性较差
2.对多条件问题的处理SQL的性能优化问题
3.维度一致性问题,group by 与select中的维度要一致
4.mysql中的日期函数方言,date_format date_sub,date_add等/year.week等
一些注意事项;
193多条件比较分别求,join
196方法二,max的应用
212自连接对dense_rank()的处理 对自连接的左表的每一行做出判断是否符合过滤的条件
213自连接对rank()的处理
自连接怎么实现row_number()
注意group by 的维度要与聚和以后要求的select的维度一致
case when 的处理 ;例如 sum(case when ) case when then when then ....的适用,if的多条件判断
如何选取:子查询 group by 自连接 join/or/and 窗口

sql
create table Student (SId varchar(10), Sname varchar(10), Sage datetime, Ssex varchar(10));
insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
insert into Student values('02' , '钱电' , '1990-12-21' , '男');
insert into Student values('03' , '孙风' , '1990-12-20' , '男');
insert into Student values('04' , '李云' , '1990-12-06' , '男');
insert into Student values('05' , '周梅' , '1991-12-01' , '女');
insert into Student values('06' , '吴兰' , '1992-01-01' , '女');
insert into Student values('07' , '郑竹' , '1989-01-01' , '女');
insert into Student values('09' , '张三' , '2017-12-20' , '女');
insert into Student values('10' , '李四' , '2017-12-25' , '女');
insert into Student values('11' , '李四' , '2012-06-06' , '女');
insert into Student values('12' , '赵六' , '2013-06-13' , '女');
insert into Student values('13' , '孙七' , '2014-06-01' , '女');

create table Course(CId varchar(10),Cname nvarchar(10),TId varchar(10));
insert into Course values('01' , '语文' , '02');
insert into Course values('02' , '数学' , '01');
insert into Course values('03' , '英语' , '03');

create table Teacher(TId varchar(10),Tname varchar(10));
insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');

create table SC(SId varchar(10),CId varchar(10),score decimal(18,1));
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 80);
insert into SC values('03' , '01' , 80);
insert into SC values('03' , '02' , 80);
insert into SC values('03' , '03' , 80);
insert into SC values('04' , '01' , 50);
insert into SC values('04' , '02' , 30);
insert into SC values('04' , '03' , 20);
insert into SC values('05' , '01' , 76);
insert into SC values('05' , '02' , 87);
insert into SC values('06' , '01' , 31);
insert into SC values('06' , '03' , 34);
insert into SC values('07' , '02' , 89);
insert into SC values('07' , '03' , 98);

表之间的关联

191.查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数

1.子查询
2.group by
3.连接

sql
--子查询
select
s0.*,s3.CId,s3.score
from student s0
join (
    select t1.SId
    from (
             select sid,
                    score
             from sc
             where CId = '01'
         ) t1
             join (
        select sid,
               score
        from sc
        where CId = '02'
    ) t2
                  on t1.SId = t2.SId
    where t1.score > t2.score
) s1 on s0.SId = s1.SId
join sc s3 on s0.SId = s3.SId;
sql
--求取01 02的分数就行了不用求全部的
select  t1.*,t3.CId,t3.score
from student t1 join (
    select SId,
           max(if(CId = '01', score, 0)) as q1,
           max(if(CId = '02', score, 0)) as q2
    from sc
    group by SId
) t2 on t1.SId = t2.SId
  join sc t3 on t1.SId = t3.SId
where t2.q1 > t2.q2 and t2.q2 !=0 and t2.q1!= 0;
sql
SELECT
	s.*,sc1.score,sc2.score
FROM
	sc AS sc1,sc AS sc2,student AS s -- 三表相连
WHERE sc1.SId = sc2.SId
  AND sc1.CId = '01' 
  AND sc2.CId ='02' 
  AND sc1.score > sc2.score 
  AND s.SId = sc1.SId  

192. 查询同时存在" 01 "课程和" 02 "课程的情况

1.子查询
2.group by
3.连接

小心注意子查询的嵌套层数,直接过滤出*也行,但符合事实上的答案

sql
select
*
from sc where SId in (
    select SId
    from sc
    where SId in (select SId from sc where CId = '01')
      and CId = '02'
);
sql
select
SId
from sc
group by SId
having  sum(if(CId='01',1,0)) >0 and sum(if(CId='02',1,0))>0;
sql
SELECT * 
FROM
	(SELECT * FROM sc WHERE sc.CId = '01') sc1, 
	(SELECT * FROM sc WHERE sc.CId = '02') sc2 
WHERE sc1.sid = sc2.sid

193.查询存在" 01 "课程但可能不存在" 02 "课程的情况(不存在时显示为 null )

同上一题

sql
select
*
from sc where  SId in (
    select SId
    from sc
    where SId in (select SId from sc where CId = '01')
      and SId not in (select SId from sc where CId = '02')
);

看了下,别人写的题目中有个可能,写错了,直接过滤出01 02 left join即可

sql
SELECT *
FROM
	(SELECT * FROM sc WHERE sc.CId = '01') sc1
LEFT JOIN
	(SELECT * FROM sc WHERE sc.CId = '02') sc2
ON sc1.sid = sc2.sid;

以后碰到这个多条件的比较直接分别查询来join,比较清晰

194.查询不存在" 01 "课程但存在" 02 "课程的情况

right join就行了

sql
SELECT *
FROM
	(SELECT * FROM sc WHERE sc.CId = '01') sc1
right join
	(SELECT * FROM sc WHERE sc.CId = '02') sc2
on  sc1.sid = sc2.sid
where  sc1.SId is not  null ;

195.查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩

1.join
2.直接关联

sql
select
t1.SId,Sname,score
from student t1
join (
    select SId, avg(score) as score
    from sc
    group by SId
    having avg(score) >= 60
) t2 on t1.SId = t2.SId;
sql
SELECT s.sid,s.Sname,avg(sc.score) avg_s
FROM sc,student s
WHERE sc.sid = s.sid 
GROUP BY sid,Sname
HAVING avg_s >= 60;

196. 查询所有课程成绩小于60分学生的学号、姓名

sql
select
SId,Sname
from student where SId in (
    select sid
    from sc
    group by sid
    having sum(if(score < 60, 0, 1)) = 0
);

方法二:如果最大的score小于60,则所有的科目成绩就都小于60

sql
select
SId,Sname
from student where SId in (
    select sid
    from sc
    group by sid
    having max(score) < 60
);

197.查询在 SC 表存在成绩的学生信息

sql
select
distinct  student.*
from student join sc on student.SId = sc.SId;

方法二:先获取在成绩表中有的sid信息,子查询where获取

198.查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null )

sql
select
t1.SId,t1.Sname,count(CId) as count_c ,sum(score) as score
from student t1 left join sc t2 on t1.sid = t2.SId
group by  t1.SId,t1.Sname;

count不存在时显示为0 ,而sum不存在则显示null

199.查有成绩的学生信息

sql
select * from student where SId in (
    select distinct sid
    from sc
    where score is not null
);

200.查询「李」姓老师的数量

sql
select
count(1)
from teacher
where Tname like '李%';

201.查询学过「张三」老师授课的同学的信息

两种思路,方法一:过滤出张三教的课程信息,多个子查询,方法二:多表join之后where

sql
select
distinct t1.*
from student t1 join sc t2 on t1.SId = t2.sid
join course t3 on t2.cid = t3.CId
join teacher t4 on t3.tid = t4.TId
where t4.Tname = '张三';

202.查询没有学全所有课程的同学的信息

sql
select
*
from student where SId not in (
    select sid
    from sc
    group by SId
    having count(1) = (select count(1) from course)
);

203.查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息

方法一:先查询存在与01学号相同课程的sid,方法二:查询02学号所有的cid,in 如果其他学号也有就是了

sql
select * from student where SId in (
    select distinct sc.sid
    from (
             select CId
             from sc
             where SId = '01'
         ) t1
             join sc on t1.CId = sc.CId
)
and SId != '01';

204.查询和" 01 "号的同学学习的课程 完全相同的其他同学的信息

比较麻烦,有没有什么简单方法???

sql
select
*
from student where  SId in (
    select SId
    from (
             select CId
             from sc
             where SId = '01'
         ) t1
             join sc on t1.CId = sc.CId
    group by sc.SId
    having count(sc.SId) = (select count(1) from sc where SId = '01')
)
and SId != '01';

205.查询没学过"张三"老师讲授的任一门课程的学生姓名

sql
select sid from student where SId not in (
    select distinct SId
    from teacher t1
             join course t2 on t1.TId = t2.TId
             join sc t3 on t2.CId = t3.CId
    where t1.Tname = '张三'
);

206.查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩

sql
select
t1.SId,t1.Sname,avg(score)
from student t1 join sc t2 on t1.SId = t2.SId
group by  t1.SId,t1.Sname
having  sum(if(score<60,1,0)) >= 2 ;

207.检索" 01 "课程分数小于 60,按分数降序排列的学生信息

sql
select
t1.*
from student t1 join  sc t2 on t1.SId = t2.SId
where  CId = '01' and score <60
order by score desc;

208.按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩

sql
select
SId,
score,
avg(score) over (partition by SId ) as avg_score
from sc
order by avg_score desc ;

方法二,先求平均值,join

209.查询各科成绩最高分、最低分和平均分

sql
select
CId,max(score),min(score),avg(score),
       concat(sum(if(score<60,1,0))/count(1),'%'),
       concat(sum(if(score<=80 and score >=60,1,0))/count(1),'%'),
       concat(sum(if(score>80,1,0))/count(1),'%')
from sc
group by CId;

210.输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列

sql
select
CId,count(distinct SId) as count_nm
from sc
group by CId
order by count_nm desc,CId;

211.按各科成绩进行排序,并显示排名, Score 重复时保留名次空缺

sql
select
CId,SId,score,rank() over (partition by CId order by score desc) rn
from sc;

自连接,哇,有点绕

sql
select
t1.CId,t1.SId,t1.score,count(t2.score) + 1 as rn
from sc t1 left join sc t2 on t1.CId =t2.CId
and  t1.score < t2.score
group by t1.CId,t1.SId,t1.score
order by t1.CId,rn asc ;

212.按各科成绩进行排序,并显示排名, Score 重复时合并名次

自连接

sql
SELECT a.*,COUNT( distinct b.score) AS `rank`
FROM SC AS a
LEFT JOIN SC AS b
ON a.score <= b.score
AND a.cid = b.cid
GROUP BY a.cid, a.sid, a.score
ORDER BY a.cid, `rank` ASC;
sql
SELECT sc.*,
       dense_rank() over (PARTITION BY cid ORDER BY score DESC) 'rank'
FROM sc

213.查询学生的总成绩,并进行排名,总分重复时保留名次空缺

sql
select
sid, sum(score),
 rank() over (order by sum(score) desc)
from sc
group by SId;
sql
select
t1.SId,t1.s1,count(t2.s2)+1 as rn
from (
         select sid,
                sum(score) as s1
         from sc
         group by SId
     ) t1  left join (
         select sid,
                sum(score) as s2
         from sc
         group by SId
    ) t2
on  t1.s1 < t2.s2
group by t1.SId,t1.s1
order by  t1.s1 desc,rn;

214.统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[60-0] 及所占百分比

sql
select
t2.SId,
t1.Cname,
concat(sum(if(score<=100 and score >=85,1,0)) / count(1),'%') as '[100-85]',
sum(if(score<=85 and score >= 70,1,0)) / count(1),
sum(if(score<=70 and score >= 60,1,0)) / count(1)  ,
sum(if(score<=60,1,0)) /count(1)
from course t1 join sc t2
group by t1.Cname,t2.SId;

215.查询各科成绩前三名的记录

--自连接有点绕啊,写了半小时,题目说是前三序列函数应该是rank,所以比较时应该是<没有等于,并且使用left join ,而对于dense_rank应该用<=且去重

sql
select
t1.CId,t1.sid,t1.score,count(t2.score) + 1
from sc t1 left join sc t2 on t1.CId = t2.CId and t1.score <  t2.score
group by  t1.CId,t1.sid,t1.score
having count(t2.score) + 1 <= 3
order by t1.CId;

216.查询每门课程被选修的学生数

sql
select
cid ,count(1) as count_n
from sc
group by CId;

217.查询出只选修两门课程的学生学号和姓名

sql
select SId,Sname from student where SId in (
    select sid
    from sc
    group by SId
    having count(1) = 2
)

218.查询男生、女生人数

sql
select Ssex,count(1) from student group by Ssex;
sql
select
sum(if(Ssex='男',1,0)) as '男生',
sum(if(Ssex='男',0,1)) as '女生'
from student;

219.查询名字中含有「风」字的学生信息

sql
select *
from student
where Sname like '%风%';

220.查询同名同性学生名单,并统计同名人数

sql
select
Sname
from student
group by Sname
having count(1) >1;

221.查询 1990 年出生的学生名单

sql
select * from student where year(Sage) ='1990';

222.查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列

sql
select
cid ,avg(score) as avg_score
from sc
group by CId
order by  avg_score desc ,CId;

223.查询平均成绩大于等于 85 的所有学生的学号、姓名和平均成绩

sql
select
t1.SId,Sname,avg(score) as avg_score
from student t1 join sc t2 on t1.SId = t2.SId
group by  t1.SId,Sname
having avg_score >= 85;

224.查询课程名称为「数学」,且分数低于 60 的学生姓名和分数

sql
select
Sname,score
from student t1 join sc t2 on t1.SId = t2.SId
join course t3 on  t2.CId =t3.CId
where t3.Cname = '数学' and score < 60;

225.查询所有学生的课程及分数情况(存在学生没成绩,没选课的情况)

sql
select
*
from student t1 left join  sc t2 on t1.SId = t2.SId;

226.查询任何一门课程成绩在 70 分以上的姓名、课程名称和分数

having 条件过滤,如果是说有一门可在70/所有的课都在70分

sql
select Cname,Sname,score
from student t1 join sc t2 on  t1.SId = t2.SId
join  course t3 on t2.CId = t3.CId
where t2.score >= 70;

都在70分

sql
select Cname,Sname,score
from student t1 join sc t2 on  t1.SId = t2.SId
join  course t3 on t2.CId = t3.CId
where  t1.SId in (
    select SId
    from sc
    group by SId
    having sum(if(score >= 70, 0, 1)) = 0
);

227.查询不及格的课程

sql
select SId,Cname
from course t1 join sc t2 on t1.CId = t2.CId
where t2.score < 60;

228.查询课程编号为 01 且课程成绩在 80 分以上的学生的学号和姓名

sql
select *
from student  where  SId in (
    select SId
    from sc
    where CId = '01'
      and score >= 80
) ;

229.求每门课程的学生人数

sql
SELECT COUNT(*),cid
FROM sc
GROUP BY cid

230.成绩不重复,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩

sql
select
t4.SId,t4.Sname,t4.Sage,t4.Ssex,max(score) as max_n
from teacher t1 join  course t2 on t1.TId = t2.TId
join  sc t3 on  t2.CId = t3.CId
join student t4 on t3.SId = t4.SId
where t1.Tname ='张三'
group by t4.SId,t4.Sname,t4.Sage,t4.Ssex
order by  max_n desc
limit 1;

方法二:分解步骤,子查询获取最高的成绩,然后join

231.成绩有重复的情况下,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩

sql
select s0.*,CId
from student s0
join (
    select SId,
           t3.CId,
           rank() over (order by score desc ) as rn
    from teacher t1
             join course t2 on t1.TId = t2.TId
             join sc t3 on t2.CId = t3.CId
    where t1.Tname = '张三'
) s1 on s1.SId = s0.SId
where rn =1;

方法二,同上面的获取最高的成绩,子查询获取

232.查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩

sql
select distinct t1.sid, t1.cid, t1.score
from sc t1 join sc t2 on t1.score = t2.score and t1.CId <> t2.CId;

方法二:先获取有重复成绩的成绩分数

sql
SELECT DISTINCT Sid,
       Cid,
       score
FROM SC WHERE score IN (
	SELECT score
	FROM SC
	GROUP BY score
	HAVING COUNT(DISTINCT Cid) > 1);

233.查询每门功成绩最好的前两名

有且只有两个人rank函数

sql
select
t1.CId,t1.SId,t1.score,count(t2.score) + 1
from sc t1 left join sc t2 on t1.CId = t2.CId and t1.score < t2.score
group by t1.CId,t1.SId,t1.score
having count(t2.score) <= 1
order by  t1.CId;

234.统计每门课程的学生选修人数(超过 5 人的课程才统计)

sql
SELECT COUNT(SId),cid
FROM sc
GROUP BY cid
HAVING COUNT(sid) > 5;

235.检索至少选修两门课程的学生学号

having过滤

sql
select SId
from sc
group by SId
having count(1)>=2;

236.查询选修了全部课程的学生信息

不存在同一门课选修多次的情况??这题好像做过了..

sql
select *
from student
where SId in (
    select SId
    from sc
    group by SId
    having count(1) = (select count(1) from course)
);

237.查询各学生的年龄,只按年份来算

sql
select *,year(now())-year(Sage) +1 as `year`
from student;

238.按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

sql
select *,year(now())-year(Sage) +
    if((date_format(now(),'%m%d')-date_format(Sage,'%m%d'))<0,1,0)
    as `year`
from student;

239.查询本周过生日的学生

sql
select * from student where  week(Sage) =
       week(now());

240.查询下月过生日的学生

sql
SELECT *
FROM Student
WHERE MONTH(Sage) = MONTH(CURDATE()) + 1;

练习题 20:建模&报表

这篇博客用来回顾和梳理一下数据仓库中的常用主题建模架构,面向分析的架构以及集成主题报表,我已经把这些报表上传至GitHub上了,有兴趣的可以看一下
地址:https://github.com/nino-laiqiu/TiTan
我在我部署在GitHub上的hexo博客中记录了一份比较完整的开发流程,有兴趣的可以看一下

241.ID-Mapping

id-mapping是用来处理多个数据来源用户一致性问题的,可以使用图计算中的连通子图来处理,但是会存在这样的问题,把本来不属于用一个人的属性连接在一起或者把一个人的划分为两个人的维度属性了,可以采用条件过滤来处理,但是这样会造成数据丢失甚至是无法解决问题
图计算不属于SQL练习这个部分,不再写了,我要解决的是匿名用户登录问题,匿名的行为日志消息应该属于哪个用户(账号)的
解决的方案:采用评分的思路,但这种解决方法仍是有问题的,比如需要多次join计算量大,比如说怎么处理一个人多账号的问题

生成一张评分表

我们设置这张评分表有如下字段
设备 账号 分数 最后一次登录时间
按照设备字段和账号字段group by 每一次会话分数就+100,取这个维度的最后登录时间,于是这就是我们的初始评分表,这张表可能会出现没有账号的行,实际中并没有什么意义,但是还是保留为好
我们取设备 账号维度下以设备为分组,取这个分组下分数最高的行与今天的log数据生成今天的guid

sql
      spark.sql(
        """
          |insert into table dw.score partition(dy="2021-02-23")
          |select
          |deviceid,account,cast(count(distinct sessionid ) * 100 as double) as score ,max(timestamp) as  timestamp
          |from db_demo1.app_event_log
          |group by deviceid,account
          |""".stripMargin).show()
生成GUID

取昨天评分表,每个设备下的最高评分,今天的log数据与其left join(条件是设备) 生成guid
我们的规则是,如果今天的log数据有账号,那么账号就作为guid,如果今天没有账号,但是昨天的数据是有账号的,那么今天的guid就是昨天这个设备下最高评分的账号了,如果都没有,那只能以今天的设备号,作为今天的guid了(这便是匿名的解决方法)

sql
spark.sql(
        """
          |
          |INSERT INTO TABLE dw.log PARTITION(dy='2021-02-23')
          |
          |select
          | regioned.account          ,
          | regioned.appid            ,
          | regioned.appversion       ,
          | regioned.carrier          ,
          | regioned.deviceid         ,
          | regioned.devicetype       ,
          | regioned.eventid          ,
          | regioned.ip               ,
          | regioned.latitude         ,
          | regioned.longitude        ,
          | regioned.nettype          ,
          | regioned.osname           ,
          | regioned.osversion        ,
          | regioned.properties       ,
          | regioned.releasechannel   ,
          | regioned.resolution       ,
          | regioned.sessionid        ,
          | regioned.timestamp        ,
          | regioned.newsession       ,
          | regioned.province   	    ,
          | regioned.city             ,
          | regioned.district         ,
          | regioned.isnew            ,
          | case
          |   when regioned.account is not null then regioned.account
          |   when idbind.account is not null then idbind.account
          |   else regioned.deviceid
          | end as guid
          |
          |from regioned left join bind on idbind.deviceid=regioned.deviceid
          |
          |""".stripMargin)
生成今天的评分表

步骤1:同步骤生成一张评分表一样,按照设备和账号维度聚合,同样会出现没有账号有设备的行
步骤2.我们把这部分提取出来,因为这些设备中可能有新设备
步骤3.我们把这些数据与昨天的评分表left join 过滤出为右边为null的数据,那么这个设备就是新设备了,我们可以给评分但是并没有什么用
步骤4.今天的评分表和昨天的评分表full join(条件是设备和账号),我们评分的标准是:如果昨天登录了,今天也登录了那么评分加起来,如果昨天登录了,但是今天没有那么评分衰减,如果昨天没有数据,但是今天有数据,那么就保留其评分与步骤三的数据union all ,就是今天的评分表了,然后不断循环

sql
spark.sql(
        """
          |INSERT INTO TABLE dw.score PARTITION(dy='2021-02-23')
          |
          |select
          |a.deviceid,
          |a.account,
          |a.timestamp,
          |a.score
          |from
          |cur_may_new a
          |left join pre_score b
          |on a.deviceid = b.deviceid
          |where b.deviceid is  null
          |
          |union all
          |
          |select
          |nvl(pre.deviceid,cur.deviceid) as deviceid, -- 设备
          |nvl(pre.account,cur.account) as account, -- 账号
          |nvl(cur.timestamp,pre.timestamp) as timestamp, -- 最近一次访问时间戳
          |case
          |when pre.deviceid is not null and cur.deviceid is not null then pre.score+cur.score
          |when pre.deviceid is not null and cur.deviceid is null then pre.score*0.5
          |when pre.deviceid is  null and cur.deviceid is not  null then cur.score
          |end as score
          |from
          |pre_score pre
          |full join
          |today_score cur
          |on pre.deviceid = cur.deviceid and  pre.account = cur.account
          |""".stripMargin).show()

242.布隆过滤器

布隆过滤器是bitmap的变形式,在大数据领域布隆过滤器能用在各种地方,比如hbase中的LSM树中就有体现,布隆过滤器的原理不在说明,值得注意布隆过滤器的误差率的计算公式,以及与去重算法Hyperloglog的对比
https://juejin.cn/post/6844903785744056333
下面举一些例子来体现一下布隆过滤器的应用,例如两张大表join怎么优化,如果由于布隆过滤器会覆盖相同组合hash映射的值,所以我们不追求误差率的情况下是可以使用它的,又比如说怎么大量数据去重,又比如说两份大文件,怎么查找出相同的数据(对于重复的只要展示一个即可,不需要展示数量特征)

新老用户标识

怎么标识今天的用户是否是老用户还是新用户,在数据量较小的情况在spark的开发环境中,比如我们使用spark的mapjoin(广播变量),还可以使用full join (left join)来实现,没有join上的就是新用户了,在数据量大的情况下我们使用布隆过滤器来优化一下,下面是布隆过滤器的示例

text
 //使用hadoop的布隆过滤器
  def hadoopBloom() {
    val filter = new BloomFilter(1000000, 5, Hash.MURMUR_HASH)
    filter.add(new Key("a".getBytes()))
    filter.add(new Key("b".getBytes()))
    filter.add(new Key("c".getBytes()))
    filter.add(new Key("d".getBytes()))

    val bool = filter.membershipTest(new Key("a".getBytes))
    val bool1 = filter.membershipTest(new Key("dwd".getBytes))
    println(bool)
    println(bool1)
  }
  //使用spark的布隆过滤器
  def sparkBloom(): Unit = {
    val spark = SparkSession.builder().config(new SparkConf().setMaster("local[*]").setAppName(this.getClass.getSimpleName)).getOrCreate()
    import spark.implicits._
    val filter = spark.sparkContext.makeRDD(List("A", "B", "C", "D", "E", "F")).toDF("alphabet").stat.bloomFilter("alphabet", 100000, 0.001)
    val bool = filter.mightContain("A")
    val bool1 = filter.mightContain("R")
    println(bool)
    println(bool1)
  }

对于新老用户问题,我们可以把昨天的用户映射到BloomFilter中,并把BloomFilter 给广播出去,使用mapPartitions一个组一个组来比较,如果在布隆过滤器中,那就是老用户,标识newuser = 0 ,否则newuser = 1

243.拉链表

拉链表就是事实表中的累计快照表,我们使用拉链表的思想能解决时间性质的问题,示例:用户连续登陆问题,来说明一下拉链表的用法与SQL处理,拉链表的处理难点是分类的逻辑比较复杂

初始

拉链表的字段如下:
首次登录时间(first_dt) guid 区间开始时间(range_start) 区间结束时间(range_end)
first_dt,guid,range_start,range_end
按照guid聚合,获取今天登陆的用户信息
guid cur_time

分类

昨天的拉链表和今天的登录用户信息 full join (字段guid),join上的是昨天登录了,今天登录了
以及已经封闭区间的了,但是今天确实登录了,这一类要单独处理
没有join上的分为以下几类
1.今天的新用户(guid)
2.昨天登录了,但是今天没有登录,range_end为9999-12-31
3.已经是封闭区间的行,今天也没有登录

处理

我们对这几种情况分别处理
没有join上的
1.昨天登录了pre.range_end = '9999-12-31' 但是今天没有登录 cur.cur_time is null
first_dt,guid,range_start保持不变,range_end改成昨天的
2.新用户的情形,昨天没有登录 pre.range_end is null ,今天登陆了
first_dt,guid,range_start,range_end分别改为今天,用户,今天,9999-12-31
3.封闭区间,今天没有登录,保持原样不变

join上的
1.昨天登录了,今天登录了即join上的,保持原样不变
2.封闭区间(之前登过,但是至少昨天没有登,但是今天登陆了),保持原样行属性不变,对于新增今天的登录这一点我们要单独处理,处理如下
从昨天的数据中获取guid的range_end 不是9999-12-31的guid和首次登录时间
与今天的数据join(字段为 guid) 如果能join上那就是之前登录过的封闭区间,但是至少昨天没有登录,今天登陆了
first_dt,guid,range_start,range_end,分别是之前的初始登录信息,guid,今天,9999-12-31

注意一下left semi join 和 join 的区别

sql
   spark.sql(
     """
       |select
       |  nvl(pre.first_dt, cur.cur_time) as first_dt,
       |  -- 如果之前存在那就取之前,之前不存在那就是新用户了
       |  nvl(pre.guid, cur.guid) as guid,
       |  nvl(pre.range_start, cur.cur_time) as range_start,
       |  case when pre.range_end = '9999-12-31'
       |  and cur.cur_time is null then pre.pre_time --  昨天登录,今天没有登录
       |  when pre.range_end is null then cur.cur_time -- 新用户(join不上的)
       |  else pre.range_end -- 封闭区间保持原样
       |  end as range_end
       |from
       |  (
       |    select
       |      first_dt,
       |      guid,
       |      range_start,
       |      range_end,
       |      dy as pre_time
       |    from
       |      dw.user_act_range
       |    where
       |      dy = '2020-12-10'
       |  ) pre full
       |  join (
       |    select
       |      guid,
       |      max(dy) as cur_time
       |    from
       |      dw.traffic_aggr_session
       |    where
       |      dy = '2020-12-11'
       |    group by
       |      guid
       |  ) cur on pre.guid = cur.guid
       |union all
       |  -- 从会话层获取今日登陆的用户
       |  -- range_end封闭且今日登陆的情况
       |select
       |  first_dt as first_dt,
       |  o1.guid as guid,
       |  '2020-12-11' as range_start,
       |  '9999-12-31' as range_end
       |from
       |  (
       |    select
       |      guid,
       |      first_dt
       |    from
       |      dw.user_act_range
       |    where
       |      dy = '2020-12-10'
       |    group by
       |      guid,
       |      first_dt
       |    having
       |      max(range_end) != '9999-12-31'
       |  ) o1 -- 从会话层取出今天登陆的所有用户
       |  left semi
       |  join (
       |    select
       |      guid
       |    from
       |      dw.traffic_aggr_session
       |    where
       |      dy = '2020-12-11'
       |    group by
       |      guid
       |  ) o2 on o1.guid = o2.guid
       |""".stripMargin).show(100,false)

244.bitmap思想

如上面的那种处理会产生大量的冗余数据,我们可以定时清除冗余数据,但是bitmap思想建模处理,可以避免这种数据冗余,bitmap表在用户登录问题上,最多只有(有多少账号/用户就有多少行),如果我们想要保留所有的历史数据,我们可以对bitmap表进行压缩,bitmap压缩中咆哮位图算法就是很好的压缩算法,这里我们采用把bit-01显示转化为long类型的数来压缩存储
bitmap生成表报的思路:使用like函数,replace函数,split()函数以及正则表达式即可解决用户登陆问题(示例),比如like获取用户连续登陆,replace把0替换为空格,获取登陆天数等,split切分获取访问间隔等

bitmap表

获取用户的登录信息,按照guid聚合,考虑存储sum来节省空间

sql
select
guid, 
sum(pow(2,datediff('2020-11-18',dt)))
from 
db_demo1.dou
group by guid
更新方法一(substr)

两种更新方法的区别在于位运算无需为原来的bitmap中的sum数据进行翻转,直接对最后一位进行操作,二方法一是需要翻转的(当然不翻转也行),对第一位操作
补全为一个月的登录情况

text
reverse(lpad(cast(bin(bitmap) as string), 31, '0'))

与今天guid的登录情况full join (字段guid)
1.今天没有登录
2.今天登陆了
3.新的guid

注意conv/bin/lpad/rpad等函数的应用

sql
with a as (
  select
    -- 会话视图层
    guid
  from
    dw.traffic_aggr_session
  where
    dy = '2020-12-17'
  group by
    guid
),
b as (
  select
    -- bitmap表
    guid,
    reverse(lpad(cast(bin(bitmap) as string), 31, '0')) as bitstr
  from
    dw.bitmp_30d
  where
    dy = '2020-12-16'
)
insert into
  table dw.bitmp_30d partition(dt = '2020-12-17')
select
  nvl(a.guid, b.guid) as guid,
  conv(
    -- conv函数把二进制转为10进制
    reverse(
      -- 反转把最近登陆反转到结尾,离今天越近数值越小
      case when a.guid is not null
      and b.guid is not null then concat('1', substr(bitstr, 1, 30)) when a.guid is null
      and b.guid is not null then concat('0', substr(bitstr, 1, 30)) when b.guid is null then rpad('1', 31, '0') end
    ),
    2,
    10
  ) as bitmap
from
  a full
  join b on a.guid = b.guid
更新方法二(位运算)

利用&的特性,1&1 =1 1&0 = 0

T+1日,用户没活跃,则如下更新:
select bin(1073741823 & cast(conv('111111111111111111111111111111',2,10)*2 as int));

T+1日,用户活跃,则如下更新:
select bin(1073741823 & cast(conv('111111111111111111111111111111',2,10)*2+1 as int));
取前三十天的位,把今天的位设置为1,距今天越近,越小,即1073741823是经过处理后的bitmap登录信息

select bin(concat( substr(lpad(bin(1),31,0),2,31) , '1') & cast(conv('111111111111111111111111111111',2,10)*2 as int));

245.漏斗模型

漏斗模型分析的处理,在SQL是比较难处理的,这里提供一种巧妙的方法:正则表达式,关于漏斗模型在Clickhouse中有自带的函数,非常方便,有兴趣的可以学习一下Clickhouse的文档,这里不再示例 https://clickhouse.tech/docs/en/

注意对regexp_extract/ regexp_replace/sort_array/collect_list/ concat_ws的使用与学习

sql
create table dw.funnel_statistic_1d
( 
  funnel_name  string,-- 漏斗的业务步骤
  guid         string,-- 用户
  comp_step    int -- 用户完成这个步骤多少步
)
partitioned by (dy string)
stored as parquet 
tblproperties("parquet.compress" = "snappy")
;

insert into table dw.funnel_statistic_1d partition(dy='2020-12-12')
select
  '浏览分享添加' as funnel_name,
  guid,
  comp_step
from
  (
    select
      guid as guid,
      -- sort_array()返回的是一个数组  regexp_extract() 只能对字符串操作
      case when regexp_extract(
        concat_ws(
          ',',
          sort_array(
            collect_list(
              concat_ws('_', cast(`timestamp` as string), eventId)
            )
          )
        ),
        '.*?(pageView).*?(share).*?(addCart).*?',
        3
      ) = 'addCart' then 3 when regexp_extract(
        concat_ws(
          ',',
          sort_array(
            collect_list(
              concat_ws('_', cast(`timestamp` as string), eventId)
            )
          )
        ),
        '.*?(pageView).*?(share).*?',
        2
      ) = 'share' then 2 when regexp_extract(
        concat_ws(
          ',',
          sort_array(
            collect_list(
              concat_ws('_', cast(`timestamp` as string), eventId)
            )
          )
        ),
        '.*?(pageView).*?',
        1
      ) = 'pageView' then 1 else 0 end as comp_step
    from
      dw.enent_app_detail
    where
      dy = '2020-12-12'
      and -- 漏斗步骤(
        (
          eventId = 'pageView'
          and properties ['pageId'] = '877'
        )
        or (
          eventId = 'share'
          and properties ['pageId'] = '791'
        )
        or (
          eventId = 'addCart'
          and properties ['pageId'] = '72'
           )
         group by guid
     )o
where
  comp_step > 0;

-- 报表案例:统计完成步骤的人数

select 
count(if(comp_step>=1,1,null)) as step_1,--完成第一步的人
count(if(comp_step>=2,1,null)) as step_2,
count(if(comp_step>=3,1,null)) as step_3,
from 
dw.funnel_statistic_1d 
where dy='2020-12-12';

246.宽表

在数据仓库架构层DWS层,采取的是大宽表集成的主题架构,这样的架构是清晰的,避免了多表join的操作,提高的性能,减少了使用难度
所谓宽表就是维度退化把维度属性增添至事实表中,并且事实表中的粒度也是不同的,不同的粒度由同一个自然键相连着,不同的粒度的事实信息采用union all 来连接,分别求取

sql
-- 源表.订单主要信息表  订单签收人信息表
-- order order_desc
-- 重要的处理事项:是否要去重,where(分区字段),
-- 可以考虑把temp单独地做成一张表,这样方便计算
with temp as (
select
  a.order_id   ,-- 订单ID
  a.order_date ,-- 订单日期
  a.user_id    , -- 用户ID
  a.order_money , -- 订单金额(应付金额)
  a.order.status , -- 订单状态(6:退货,7:拒收)
  a.pay_type , -- 订单支付类型
  b.area_name ,-- 收货人地址
  b.address ,-- 手工地址
  b.coupen_money -- 代金券金额
from 
  order a join order_desc b on a.user_id = b.user_id
)

-- 模块一
select 
  user_id , -- 用户
  min(order_date) , -- 首单
  max(order_date) , -- 末单日期
  datediff('2020-12-12',min(order_date)) , -- 首单距今时间
  datediff('2020-12-12',max(order_date)) , -- 末单距今时间
  count(if(datediff('2020-12-12',order_date) <=30,1,null)), -- 最近三十天购买次数
  sum(if(datediff('2020-12-12',order_date) <=30,order_money,0)), -- 最近三十天购买的金额
  count(if(datediff('2020-12-12',order_date) <=60,1,null)), -- 最近六十天购买次数
  sum(if(datediff('2020-12-12',order_date) <=60,order_money,0)), -- 最近六十天购买的金额
  count(if(datediff('2020-12-12',order_date) <=90,1,null)), -- 最近九十天购买次数
  sum(if(datediff('2020-12-12',order_date) <=90,order_money,0)), -- 最近九十天购买的金额
  min(order_money) , -- 最小的金额
  max(order_money) , -- 最大的金额
  count(if(order_status != '6' and order_status != '7',1,null)) , -- 累计消费次数(不含推拒),注意是6.7是字符串
  sum(if(order_status != '6' and order_status != '7',order_money,0)) , -- 累计代金券金额(不含推拒)
  avg(order_money) , -- 平均订单金额
  avg(if(datediff('2020-12-12',order_date) <=90,order_money,null)) -- 最近九十天的平均的订单的金额           
from
  temp
group by user_id -- 用户画像标签计算

-- 模块二:常用地址
select 
  user_id, 
  common_address -- 常用地址
from 
(
select 
  user_id  ,-- 用户
  concat_ws(' ',address,area_name ) as common_address  ,-- 常用地址(可能为null)
  row_number() over(partition by user_id order by count(1) desc rows between unbounded preceding  and current row) as rn
from
  temp 
group by user_id,concat_ws(' ',address,area_name )
) o 
where o.rn = 1

-- 模块三:常用支付方式
select
  user_id, -- 用户ID
  pay_type,-- 常用支付方式
from 
(
select 
  user_id,
  pay_type,
  row_number() over(partition by user_id order by num_pay desc rows between unbounded preceding  and current row ) as rn
from 
(
select 
  user_id,
  pay_type,
  count(1) as num_pay
from
  temp
group by user_id,pay_type
) o 
) o1
where rn = 1 

-- 模块四:购物车
select 
  user_id , -- 用户ID
  count(1),      --最近30天加购次数
  sum(number) ,-- 最近30天加购商品件数
  sum(if(submit_time is not null ,number ,0)) -- 最近30天提交次数
from
  cart -- 购物车信息表
where datediff('2020-12-12',add_time) <= 30 -- 先过滤
group  by user_id

-- 模块五:可能有的用户订单购物车某一部分没有,考虑是否这两张表的uid作为数据链接的基础
with temp5 as (
select  user_id from order 
union 
select  user_id from cart
)

-- 整合五个模块即可求出

247.增量与全量

增量,全量导入数据以及如何更新维度表,事实表的更新,以及增添属性应该如何处理在之前的文章里已经写过了,不再写了

248.归因分析

归因分析,是一类循环问题,我们用SQL来处理是复杂的,难度较高的,所以这里我提供在spark开发环境下的如何处理循环问题,对于归因分析本身就有多种的分析方法:
末次触点分析,首次触点分析,末次非直接点击归因,线性归因分析,U型归因分析等等,这里我们简单地示例一下时间衰减归因分析在spark中是如何处理的,至于其他的分析方法在我的hexo博客中已经有了简单的示例了,这里不再写了
https://nino-laiqiu.github.io/2020/12/10/Data-System-Warehouse/

text
 val decay = (event_list: mutable.WrappedArray[String], attribute: mutable.WrappedArray[String]) => {
    var tuple: (List[String], List[String]) = event_list.toList.map(_.split("_")(1)).span(_ != "e6")
    var buffer = ListBuffer[(String, Double)]()
    while (tuple._2.nonEmpty) {
      if (tuple._1.nonEmpty) {
        val list = tuple._1.toSet.toList
        val seq = for (i <- list.indices) yield Math.pow(0.9, i)
        val tuples1: immutable.Seq[(String, Double)] = for (j <- list.indices) yield (list(j), seq(j) / seq.sum)
        for (elem <- tuples1) {
          buffer += elem
        }
      }
      tuple = tuple._2.tail.span(_ != "e6")
    }
    buffer
  }

249.报表

报表的开发基于DWS层的集成主题建模架构的,这里简单的示例一些主题报表SQL的写法

用户访问间隔

SQL使用偏移量函数,注意对时间范围的规整

sql
//用户访问间隔分析
//guid,first_dt,rng_start,rng_end
object UserAccessInterval {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().appName(this.getClass.getSimpleName).master("local[*]").getOrCreate()
    val schema = new StructType()
      .add("guid", DataTypes.LongType)
      .add("first_dt", DataTypes.StringType)
      .add("rng_start", DataTypes.StringType)
      .add("rng_end", DataTypes.StringType)
    val frame = spark.read.schema(schema).csv("file:///C:\\Users\\hp\\IdeaProjects\\TiTan\\dataware\\src\\main\\resources\\UserAccessInterval.csv")
    frame.createTempView("tmp")
    /*1.过滤出rng_end时间与今天相比小于30的数据
    2.把rng_end为9999-12-31的日期改成2020-03-14
    3.如果first_dt与今天相比大于30天则更改为今天的日期-30,否则不变*/
    val frame1 = spark.sql(
      """
        |select
        |  guid,
        |  if(datediff('2020-03-14',rng_start)>=30,date_sub('2020-03-14',30),rng_start) as rng_start,
        |  if(rng_end = '9999-12-31','2020-03-14',rng_end) as rng_end
        |from
        |  tmp
        |where datediff('2020-03-14',rng_end) <=30
        |""".stripMargin)

    //统计登陆间隔
    //按用户来分组
    val guidrdd = frame1.rdd.map(row => {
      val guid = row.getAs[Long]("guid")
      val rng_start = row.getAs[String]("rng_start")
      val rng_end = row.getAs[String]("rng_end")
      (guid, (rng_start, rng_end))
    }).groupByKey()

    val value = guidrdd.flatMap(data => {
      val guid = data._1
      val sorted = data._2.toList.sortBy(_._2)
      //统计间隔为0的次数
      val list: List[(Long, Int, Int)] = for (elem <- sorted) yield (guid, 0, datediff(elem._1, elem._2))

      //统计间隔为N的次数(要排序),用后一个的rng_start- 前一个的 rng_end
      val list1 = for (i <- 0 until sorted.length - 1) yield (guid, datediff(sorted(i)._2, sorted(i + 1)._1), 1)
      list ++ list1
    })
    import spark.implicits._
    import org.apache.spark.sql.functions._
    value.toDF("guid", "interval", "times")
      .groupBy("guid", "interval").agg(sum("times") as "times")
      .show(100, false)
  }

  //时间相减
  def datediff(date1: String, date2: String): Int = {
    val sdf = new SimpleDateFormat("yyyy-MM-dd")
    val s1: Date = sdf.parse(date2)
    val s2: Date = sdf.parse(date1)
    ((s1.getTime - s2.getTime) / (24 * 60 * 60 * 1000)).toInt
  }
}
复购率分析
sql
-- 复购率分析
-- 需要两张表 订单主要信息表 order 订单商品详情表 order_goods
-- 订单 用户id 商品 品类
with x as (
  select
    t1.order_id,
    t1.use_id,
    t2.good_id,
    t2.type_id
  from
    (
      select
        order_id,
        use_id
      from
        order
      where
        dy = '2020-12-12'
    ) t1
    join order_goods t2 on t1.order_id = t2.order_goods
)
select
  '2020-12-12' as dy,
  --今日时间
  type_id,
  -- 品类
  count(use_id) -- 购买该品类多少人,已经对人进行了去重了,上一步group by use_id
  count(if(user_cnt >= 2, 1, null)) as time_2,
  -- 统计购买次数大于2次的人的个数
  count(if(user_cnt >= 3, 1, null)) as time_3,
from
  (
    select
      -- 一个用户购买多少该品类
      type_id,
      use_id,
      count (distinct order_id) as user_cnt 
      -- 为什么要对order_id 去重因为一个品类一条数据,一个用户一次可能购买多个品类
    from
      x
    group by
      use_id,
      type_id
  ) o
group by
  o.type_id

-- 复杂报表分析
-- 表报分析
-- 店铺 地区 月份 月销售金额 同地区同月份所有店铺销售金额 该店铺到该月的累计金额
-- 数据
shop  province    provincetable
shop month sale   shoptable

with y as (
  with x as (
    select
      a.shop,
      max(b.province) as province,
      a.month,
      sum(a.sale) as sale_cnt
    from
      shoptable a
      join provincetable b on a.shop = b.shop
    group by
      a.shop,
      a.month
  )
  select
    -- 增加字段累计金额
    shop,
    province,
    month,
    sale_cnt,
    sum(sale_cnt) over(
      partition by shop
      order by
        month rows between unbounded preceding
        and current row
    ) as shop_account_cnt
  from
    x
) -- 按地区和月份进行分组,求同地区同月份下所有店铺的销售金额
select
  y.shop,
  y.province,
  y.sale_cnt,
  z.province_sale,
  y.shop_account_cnt
from
  (
    select
      province,
      month,
      sum(s.sale) as province_sale
    from
      shoptable s
      join provincetable p on s.shop = p.shop
    group by
      s.month,
      p.province
  ) z
  join y on z.province = y.province
  and z.month = y.month
用户偏好
sql
-- 用户购物偏好标签
-- 关联三张表
-- 订单表 order 订单商品详情表 orders_good 商品描述表 goods
-- 做一张中间表存储三张表关联的结果

create table tag(
user_id string ,
first_cat_name  string ,
second_cat_name string ,
third_cat_name string,
brand_id_name  string,
)
stored as parquet tblproperties("parquet.compress" = "snappy")

insert  into  tag 
select 
  order.user_id, -- 用户ID
  goods.first_cat_name, -- 一类标签
  goods.second_cat_name,
  goods.third_cat_name,
  goods.brand_id_name -- 商品标签
from 
  order 
join orders_good on order.order_id = orders_good.order_id
join goods on  orders_good.goods_id = goods.sku_id

with tmp1 as (
select 
  user_id,
  first_cat_name
from 
(
select 
  user_id,
  first_cat_name,
  row_number() over(partition by user_id order by count(1)) as rn-- 标签数
from
  tag
group by user_id,first_cat_name
)
where rn = 1
),
tmp2 as (
select 
  user_id,
  second_cat_name
from 
(
select 
  user_id,
  second_cat_name,
  row_number() over(partition by user_id order by count(1)) as rn 
from
  tag
group by user_id,second_cat_name
)
where rn = 1
),
tmp3 as (
select 
  user_id,
  third_cat_name
from 
(
select 
  user_id,
  third_cat_name,
  row_number() over(partition by user_id order by count(1)) as rn 
from
  tag
group by user_id,third_cat_name
)
where rn = 1
),
tmp4 as (
select 
  user_id,
  brand_id_name
from 
(
select 
  user_id,
  brand_id_name,
  row_number() over(partition by user_id order by count(1)) as rn 
from
  tag
group by user_id,brand_id_name
)
where rn = 1
)

select 
  tmp1.user_id, -- 用户ID
  tmp1.first_cat_name as common_first_cat, -- 最常购买的一类标签
  tmp2.second_cat_name as common_second_cat,
  tmp3.third_cat_name as common_third_cat, -- 最常购买的三类标签
  tmp4.brand_id_name as common_brand_id -- 最常购买的标签
from 
  tmp 
join  tmp2 on tmp1.user_id = tmp2.user_id
join  tmp3 on tmp1.user_id = tmp3.user_id
join  tmp4 on tmp1.user_id = tmp4.user_id

250.etl处理

etl的处理包含数据的导入导出(全量/增量),数据的清洗与标准化,数据的治理,etl元数据的治理,我的关注点在数据的治理和分类
这是一个大的模块,以后再写

练习题 21:Hive练习题

这里的题目都是之前博客篇hive实践里面的题目,来源于简书 csdn 公众号 ,其中的题目都是常规题,较好的巩固了case when 语法 高级聚合函数 行转列/列转行 窗口函数/窗口大小

hive远程连接步骤:要开启hdfs和hive的元数据管理,后台运行
hive --service metastore &
hiveserver2 &

251.集合数据类型

建表

sql
create table test(
    MobilePlatform string,
    APP array<string>,
    name map<string,int>,
    address  struct<street:string, city:string>
)
row format delimited fields terminated by ','
collection items terminated by '_'
map keys terminated by ':'
lines terminated by '\n';

语句的解释

sql
1.行列分隔符
2.MAP STRUCT 和 ARRAY 的分隔符(数据分割符号)
3.MAP中的key与value的分隔符
4.行分隔符

数据如下

text
apple,jianshu_weibo,xiaoming:19_xiaohua:17,1000A_zhongguo
songsong,bingbing_lili,xiao song:18_xiaoxiao song:19,hui long guan_beijing

查询结果与查询方法

text
apple	["jianshu","weibo"]	{"xiaoming":19,"xiaohua":17}	{"street":"1000A","city":"zhongguo"}
songsong	["bingbing","lili"]	{"xiao song":18,"xiaoxiao song":19}	{"street":"hui long guan","city":"beijing"}

array的查询方法使用下标

sql
select APP[1] from listtest;

map的查询方法使用,查询指定K

sql
select name['xiaoxiao song']  from listtest;

struct的查询方法,使用属性.K

sql
select  address.street from listtest;

252.窗口语法

over关键字用来指定函数执行的窗口范围,若后面括号中什么都不写,则意味着窗口包含满足WHERE条件的所有行,窗口函数基于所有行进行计算;如果不为空,则支持以下4中语法来设置窗口。
①window_name:给窗口指定一个别名。如果SQL中涉及的窗口较多,采用别名可以看起来更清晰易读;
②PARTITION BY 子句:窗口按照哪些字段进行分组,窗口函数在不同的分组上分别执行;
③ORDER BY子句:按照哪些字段进行排序,窗口函数将按照排序后的记录顺序进行编号;
④FRAME子句:FRAME是当前分区的一个子集,子句用来定义子集的规则,通常用来作为滑动窗口使用

例如

sql
select name,orderdate,cost,
sum(cost) over() as fullagg, --所有行相加
sum(cost) over(partition by name) as fullaggbyname, --按name分组,组内数据相加
sum(cost) over(partition by name order by orderdate) as fabno, --按name分组,组内数据累加 
sum(cost) over(partition by name order by orderdate rows between unbounded preceding and current row) as mw1   --和fabno一样,由最前面的起点到当前行的聚合 
sum(cost) over(partition by name order by orderdate rows between 1 preceding and current row) as mw2,   --当前行和前面一行做聚合 
sum(cost) over(partition by name order by orderdate rows between 1 preceding and 1 following) as mw3,   --当前行和前边一行及后面一行 
sum(cost) over(partition by name order by orderdate rows between current row and unbounded following) as mw4  --当前行及后面所有行 
over (order by score range between 2 preceding and 2 following) 窗口范围为当前行的数据幅度减2加2后的范围内的数据求和。
from order; 

控制窗口大小的使用
PRECEDING:往前
FOLLOWING:往后
CURRENT ROW:当前行
UNBOUNDED:起点,UNBOUNDED PRECEDING 表示从前面的起点, UNBOUNDED FOLLOWING:表示到后面的终点

253.窗口的简单使用

TopN案例
sql
select 
*
from 
(
select 
*,
row_number() over(partition by subject order by score desc) rmp
from score
) t
where t.rmp<=3;
连续登陆案例
sql
1,2020-01-01
1,2020-01-02
1,2020-01-03
1,2020-01-04
1,2020-01-07
1,2020-01-08
9,2020-01-08
7,2020-01-15
3,2020-01-09
4,2020-01-12
1,2020-01-09
2,2020-02-09
2,2020-02-10
2,2020-02-11
2,2020-02-12
2,2020-02-14
2,2020-02-15
4,2020-01-11
4,2020-01-13
4,2020-01-15

建表与SQL

sql
create table sigin1(
userid int,
sigindate string
)row format delimited
fields terminated by ",";
load data local inpath '/root/user1.txt' into table sigin1;
sql
select
userid
from (
         select userid,
                date_sub(sigindate , rn) as num_rn
         from (
                  select *, row_number() over (partition by userid order by sigindate) as rn from sigin1
              ) t1
     ) t2
group by userid,num_rn
having count(1)  >= 3 ;
练习

测试数据

sql
jack,2017-01-01,10
tony,2017-01-02,15
jack,2017-02-03,23
tony,2017-01-04,29
jack,2017-01-05,46
jack,2017-04-06,42
tony,2017-01-07,50
jack,2017-01-08,55
mart,2017-04-08,62
mart,2017-04-09,68
neil,2017-05-10,12
mart,2017-04-11,75
neil,2017-06-12,80
mart,2017-04-13,94

建表与需求

sql
create table business
(
name string, 
orderdate string,
cost int
)ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

加载数据

sql
load  data local inpath "/root/business.txt" into table business;
1、查询在2017年4月份购买过的顾客及总人数(不去重)
sql
select
collect_set(name) as name,count(1) as count_p
from business
where substr(orderdate,1,7) = "2017-04";
2、查询顾客的月购买总额,查询月购买明细
sql
???直接group by 就行了,这里是练习一下窗口
select
name,total_amount
from
(
select
*,
row_number() over (partition by name ,substr(orderdate,1,7)) as rank
from
(
select
*,
sum(cost) over(partition by name,substr(orderdate,1,7) ) total_amount
from
business) t1 )t2
where rank =1;
3、查询顾客的购买明细及到目前为止每个顾客购买总金额
sql
select *,
sum(cost) over (partition by name order by orderdate rows between unbounded preceding  and current row )
from business;
4、查询顾客上次的购买时间
sql
select
*,
lag(orderdate,1,0) over (partition by name order by orderdate) as Thelastimetobuy
from business;
5、查询前20%时间的订单信息
sql
select
name,orderdate,cost
from
(
select
*,
ntile(5) over (order by  orderdate) as portion
from business) t1
where portion =1;

254.行转列,列转行

CONCAT(STRING A ,STRINFG B):返回字符串的连接后的结果
CONCAT_WS(separator, str1, str2,…):这是一个特殊的CONCAT(),第一个参数是分隔符
COLLECT_SET():函数只接受基本数据类型,它的主要作用是将某字段的值进行去重汇总,产生array类型字段
CONCAT_WS(SEPARATOR ,COLLECT_SET(column)) ===>GROUP_CONCAT()函数

数据

sql
孙尚香,白羊座,A
司马懿,射手座,A
吕布,白羊座,B
貂蝉,白羊座,A
许褚,射手座,A

需求

sql
射手座,A    司马懿|许褚
白羊座,A    孙尚香|貂蝉
白羊座,B    吕布

建表和SQL

sql
create table person_info(
name string,
constellation string,
blood_type string)
row format delimited fields terminated by ",";
load data local inpath "/root/f.txt" into table person_info;
sql
select
//concat(constellation,",",blood_type),
concat_ws(",",constellation,blood_type) as list,
concat_ws("|",collect_set(name)) as name
from
person_info
group by  constellation,blood_type;

EXPLODE(col):将hive一列中复杂的array或者map结构拆分成多行。
LATERAL VIEW:用于和split, explode等UDTF一起使用,它能够将一列数据拆成多行数据,在此基础上可以对拆分后的数据进行聚合
split(str , 分隔符):返回一个数组

SQL

数据

sql
《疑犯追踪》 悬疑,动作,科幻,剧情
《Lie to me》	悬疑,警匪,动作,心理,剧情
《战狼2》 战争,动作,灾难

需求

sql
《疑犯追踪》      悬疑
《疑犯追踪》      动作
《疑犯追踪》      科幻
《疑犯追踪》      剧情
《Lie to me》   悬疑
《Lie to me》   警匪
《Lie to me》   动作
《Lie to me》   心理
《Lie to me》   剧情
《战狼2》        战争
《战狼2》        动作
《战狼2》        灾难

建表与SQL

sql
create table movie_info(
movie string,
category array<string>)
row format delimited fields terminated by "|"
collection items terminated by ",";

load data local inpath "/root/g.txt" into table movie_info;
sql
select
movie
result
from movie_info
lateral view
explode(category) result as result

255.case when(if)语法

CASE 字段 WHEN 值1 THEN 值1 [WHEN 值2 THEN 值2] [ELSE 值] END
CASE WHEN 条件表达式 THEN 值1 [WHEN 条件表达式 [and or] 条件表达式THEN 值2] [ELSE 值] END

256.case when的简单使用

数据与需求

sql
(用户工资组成表,基本工资,基金,提成)
1,2000,3000,1500,1
2,5000,500,1000,2
3,1500,1000,3000,2
4,3000,6000,8000,3
5,1500,2000,1800,1
6,2500,1000,1900,1
(部门表)
1,销售
2,技术
3,行政
(员工信息表)
1,zs,M,28
2,ww,F,36
3,zl,F,48
4,pp,M,44
5,wb,M,32
6,TQ,F,32

create table gz(
uid int,
jb int,
jj int,
tc int,
deptno int
)
row format delimited fields terminated by ",";
load data local inpath "/root/gz.txt" into table gz;

create table bm(
deptno string ,
name string
)
row format delimited fields terminated by ",";
load data local inpath "/root/bm.txt" into table bm;

create table yg(
uid int,
name string,
gender string,
age int
)
row format delimited fields terminated by ",";
load data local inpath "/root/yg.txt" into table yg;

1.求出公司中每个员工的姓名 和 三类收入中最高的那种收入的类型(greatest()函数)
with x as (
select
uid, greatest(jb, jj, tc)as `max`,
//case  when   greatest(jb, jj, tc) = jb then 'jb'  when greatest(jb, jj, tc) = jj then 'jj' when  greatest(jb, jj, tc) = tc then 'tc' else '_' end  as  gz_category,
case   greatest(jb, jj, tc)  when jb then 'jb' when  jj then 'jj' when tc then 'tc' else '_' end  as gz_category1
from gz )
select  yg.uid,max,gz_category1
from  yg  join  x on yg.uid = x.uid;

2.求出公司中每个岗位的薪资总和
with x as (
select
deptno,
sum(jj+tc+jb)  sum_gz
from
gz
group by deptno)
select
bm.name,x.sum_gz
from bm
join  x on x.deptno = bm.deptno;

3.求出公司中不同性别、不同年龄阶段(20-30,31-40,41-50)的员工薪资总和
with x as
(
select
uid,
gender,
case when age>20 and age <=30 then '20-30' when age>30 and age<=40 then '31-40' when age > 41 and age <=50 then '41-50' else '_' end  as stage
from yg )
select
gender,stage,sum(jb+jj+tc) as `max`
from  gz  join  x  on gz.uid = x.uid
group by  x.gender,x.stage
order by stage desc ;

257.一道面试题

数据与需求

sql
现有这么一批数据,现要求出:  
每个用户截止到每月为止的最大单月访问次数和累计到该月的总访问次数  
三个字段的意思:  
用户名,月份,访问次数 
A,2015-01,5
A,2015-01,15
B,2015-01,5
A,2015-01,8
B,2015-01,25
A,2015-01,5
A,2015-02,4
A,2015-02,6
B,2015-02,10
B,2015-02,5
A,2015-03,16
A,2015-03,22
B,2015-03,23
B,2015-03,10
B,2015-03,11
create table if not exists infos(name string, date string, ftime int) 
row format delimited fields terminated by ",";
load data local inpath "/root/j.txt" into table infos;

sql(窗口写法)

sql
select
name,mydate,
max(t1.ints) over (partition by name order by mydate),
t1.ints,
sum(ints) over (partition by name order by mydate rows  between  unbounded preceding and  current row )
from
(
select
name,mydate,sum(ints) as ints
from infos1
group by  name,mydate) t1;

sql(考虑使用自连接实现)
//核心where datea <= dateb
select nameb, dateb, visitb,
max(visita) as max_visit,
sum(visita) as sum_visit
from (
select
a.name as namea,
a.mydate as datea,
a.visit as visita,
b.name as nameb,
b.mydate as dateb,
b.visit as visitb
from (select name,mydate,sum(ints) as visit from infos1 group by name,mydate) a join
(select name,mydate,sum(ints) as visit from infos1 group by name,mydate)  b
on a.name = b.name
 ) t1
where datea <= dateb
group by nameb, dateb, visitb;

258.分区和分桶

分区

案例

数据user.txt

sql
u001 ZSS 23 M beijing
u002 YMM 33 F nanjing
u003 LSS 43 M beijing
u004 ZY 23 F beijing
u005 ZM 23 M beijing
u006 CL 23 M dongjing
u007 LX 23 F beijing
u008 YZ 23 M beijing
u009 YM 23 F nanjing
u010 XM 23 M beijing
u011 XD 23 F beijing
u012 LH 23 M dongjing

建普通表语句

sql
create  table  if not exists  tb_user(
uid string ,
name  string ,
age int ,
gender string ,
address string
)
row format delimited fields  terminated by  " " ;

加载数据

sql
load data local  inpath  "/root/user.txt"  into table  tb_user ;

创建目标表

sql
create  table  if not exists  tb_p_user(
uid string ,
name  string ,
age int ,
gender string ,
address string
)
partitioned  by (addr string)
row format delimited fields  terminated by  " " ;

开启动态分区设置

sql
set hive.exec.dynamic.partition=true ;
set hive.exec.dynamic.partition.mode= nonstrict;  可以从普通表中导入数据

插入数据(这里是全部插入,也可以插入普通表的部分字段)

sql
普通表5个字段
分区表 5个主字段 1 个分区字段
插入数据的时候字段个数类型一致  最后一个字段就是分区字段 
insert into tb_p_user partition(addr) select uid , name , age , gender , address,address  from  tb_user ;
分桶

分区针对的是数据的存储路径;分桶针对的是数据文件,
分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑
分桶对数据的处理比分区更加细粒度化;
分桶和分区两者不干扰,可以把分区表进一步分桶;

sql
create table stu_buck(id int, name string)
clustered by(id)
into 4 buckets
row format delimited fields terminated by '\t';

set hive.enforce.bucketing = true;

load data local inpath '/root/e.txt' into table
stu_buck;

259.小文件处理方法

set hive.merge.mapfiles = true ##在 map only 的任务结束时合并小文件
set hive.merge.mapredfiles = false ## true 时在 MapReduce 的任务结束时合并小文件
set hive.merge.size.per.task = 25610001000 ##合并文件的大小
set mapred.max.split.size=256000000; ##每个 Map 最大分割大小
set mapred.min.split.size.per.node=1; ##一个节点上 split 的最少值
set hive.input.format=org.apache.hadoop.hive.ql.io.CombineHiveInputFormat; ##执行 Map 前进行小文件合并

每个Map最大输入大小(这个值决定了合并后文件的数量)

text
set mapred.max.split.size=256000000;

一个节点上split的至少的大小(这个值决定了多个DataNode上的文件是否需要合并)

text
set mapred.min.split.size.per.node=100000000;

一个交换机下split的至少的大小(这个值决定了多个交换机上的文件是否需要合并)

text
set mapred.min.split.size.per.rack=100000000;

执行Map前进行小文件合并

text
set hive.input.format=org.apache.hadoop.hive.ql.io.CombineHiveInputFormat;

===设置map输出和reduce输出进行合并的相关参数:

设置map端输出进行合并,默认为true

text
set hive.merge.mapfiles = true

设置reduce端输出进行合并,默认为false

text
set hive.merge.mapredfiles = true

设置合并文件的大小

text
set hive.merge.size.per.task = 256*1000*1000

当输出文件的平均大小小于该值时,启动一个独立的MapReduce任务进行文件merge。

text
set hive.merge.smallfiles.avgsize=16000000

用来控制归档是否可用

sql
set hive.archive.enabled=true;

通知Hive在创建归档时是否可以设置父目录

sql
set hive.archive.har.parentdir.settable=true;

控制需要归档文件的大小

sql
set har.partfile.size=1099511627776;

使用以下命令进行归档

sql
ALTER TABLE srcpart ARCHIVE PARTITION(ds='2020-04-08', hr='12');

对已归档的分区恢复为原文件

sql
ALTER TABLE srcpart UNARCHIVE PARTITION(ds='2020-04-08', hr='12');

注意,归档的分区不能够INSERT OVERWRITE,必须先unarchive

260.补充事项

substr(a,b):从字符串a中,第b位开始取,取右边所有的字符
substr(a,b,c):从字符串a中,第b为开始取,取c个字符,b可为负数从后面数

str_to_map(‘a:1,b:2,c:3’);字符串转map
select size(str_to_map(‘a:1,b:2,c:3’));返回map的元素个数
map_keys(str_to_map(‘a:1,b:2’));返回key

unix_timestamp() 日期转换为当前时间戳
from_unixtime(t1,yyyy-MM-dd HH:mm:ss)时间戳转变为日期格式
from_unixtime(unix_timestamp(date_created),yyyy-MM-dd HH:mm:ss)来规范时间的格式

练习题 22:每月十题(一)

该主题告一段落,市面上的SQL题大致我这个主题基本都囊括了,入门绰绰有余,剩余的,这个主题,我争取每个月更新一篇,主要是文本处理,窗口处理,多表处理,多条件处理,另类写法SQL/HQL,其中的题目来源来自面试题 公众号 社区

261.窗口函数打标签

sql
create table miaoying (
     id int,data int
);
insert into miaoying values (1,3),(2.,null),(3,null),(4,null),(5,5),(6,null),(7,null),(8,6),(9,null);

select *
from miaoying;

有列id,数据(data),id为主键,规则如下,data中有null的处理规则:如果null行离上面的近就取上面的不为空的数据,如果离下面的近,就取下面的不为空的数据,如果奇数的情况的处理则归属上面,请写出SQL
两种方法一个是array第二种是拉链表的思想,拉链表有两种方法,方法一是直接sum相加,第二种是对null和非null打标签(注意尝试不同的标签打法)

提供一种写法

sql
with y  as (select x.id,x.data,x.rn ,lead(data,1,data)  over (order by id) as lead_n from (
                                                                 select * ,sum(data) over(order by id) as rn  from miaoying

                                                                    ) x  where data is not null )
select t2.id,
       case when row_n <= round(count_n/2) then y.data else y.lead_n end as data
from
     (
select * ,
       row_number() over (partition by t1.rn order by t1.id) as row_n,
       count(t1.rn) over (partition by t1.rn) as count_n
from (
select * ,sum(data) over(order by id) as rn  from miaoying )t1 where  t1.data is null ) t2
join y on t2.rn = y.rn
union  all
select id,data from miaoying where  data is not null

对于如何求中位数,可以使用正序和逆序或者where条件来判断

262.分组与窗口

sql
create table mioaying1 (
    id int,shoe varchar(1)
);
insert into mioaying1 values (1,'白'),(2,'白'),(3,'白'),(4,'红'),(5,'黑'),(6,'绿'),(7,'绿');

有id,鞋子的颜色,求第三列

text
1	白 1
2	白 2
3	白 3
4	红 1
5	黑 1
6	绿 1
7	绿 2

提供一种方法,偏移打标签

sql
select id,shoe,row_number() over (partition by rn order by id) as number
from (
         select id, shoe, sum(log) over (order by id) as rn
         from (
                  select id, shoe, case when shoe != log then 1 else 0 end as log
                  from (
                           select *, lag(shoe, 1, 1) over () as log
                           from mioaying1
                       ) t1
              ) t2
     ) t3;
sql
//注意在打标签0/1是要尝试多种打法,可能答案就出来了

263.条件过滤

sql
create table a21210226 (
    a int ,b int
);

insert  into a21210226 values (1,2),(1,5),(2,1),(2,3),(2,5),(3,4),(3,2),(3,5);

a->b是一对多的关系,找出b中同时存在3 5 的 a

sql
--子查询
select  distinct  a
from a21210226
where  a in  (select a from a21210226 where b =3 )
and a in  (select a from a21210226 where b =5 );
sql
--having的过滤,好像不太对,在求取之前要去重一下
select a
from a21210226
group by a
having  sum(if(b in (3,5) ,1,0)) =2;
sql
-- join连接
select t1.a
from a21210226  t1 join  a21210226 t2 on  t1.a = t2.a and t1.b =3 and t2.b =5 ;
sql
-- having过滤方法二,也得先去重,防止同一个A有多个相同的B
select a
from (
select  a,b from a21210226 where b =3 or b =5 ) t1
group by a
having count(1) >= 2;

264.打标签

sql
CREATE TABLE b20210226 
(TIME INT,
 NAME VARCHAR(5),
 COMPLETE VARCHAR(5)
)
  
INSERT INTO b20210226 VALUES(1,'1','0');
INSERT INTO b20210226 VALUES(2,'1','1');
INSERT INTO b20210226 VALUES(3,'1','1');
INSERT INTO b20210226 VALUES(4,'1','1');
INSERT INTO b20210226 VALUES(5,'1','0');
INSERT INTO b20210226 VALUES(6,'1','0');
INSERT INTO b20210226 VALUES(7,'1','1');
INSERT INTO b20210226 VALUES(8,'1','1');
INSERT INTO b20210226 VALUES(2,'3','1');
INSERT INTO b20210226 VALUES(3,'3','1');
INSERT INTO b20210226 VALUES(4,'3','1');
INSERT INTO b20210226 VALUES(5,'3','0');
INSERT INTO b20210226 VALUES(6,'3','1');
INSERT INTO b20210226 VALUES(7,'3','1');
INSERT INTO b20210226 VALUES(8,'3','0');

需要统计每组(NAME)连续时间(TIME)内的连续完成数(COMPLETE),其中有某一时间的完成数为0就重新计算

sql
select
TIME,NAME,COMPLETE ,row_number() over (partition by NAME,rn_1 order by  TIME) as re
from (
         select TIME,
                NAME,
                COMPLETE,
                sum(tag) over (order by rn ) rn_1
         from (
                  select *, if(COMPLETE = '0', 1, 0) as tag, row_number() over (order by NAME) as rn
                  from b20210226
              ) t1
     ) t2
where  COMPLETE =1

union  all

select *,'0'
from b20210226
where  COMPLETE ='0'
order by NAME,re;

学习一下,我本来的写法是对为0的单独处理,事实上在求出结果之后if来判断一下,即可,我怎么没想到......

sql
select TIME,NAME,COMPLETE,if(COMPLETE = '0',0,re)
from (
         select TIME,
                NAME,
                COMPLETE,
                row_number() over (partition by NAME,COMPLETE,rn) as re
         from (
                  select *, TIME - row_number() over (partition by NAME,COMPLETE order by TIME) as rn
                  from b20210226
              ) t1
     ) t2
order by NAME,TIME;

改进一下

sql
select
TIME, NAME, COMPLETE, if(COMPLETE ='0',0,re)
from (
select
TIME,NAME,COMPLETE ,row_number() over (partition by NAME,COMPLETE,rn_1 order by  TIME) as re
from (
         select TIME,
                NAME,
                COMPLETE,
                sum(tag) over (order by rn ) rn_1
         from (
                  select *, if(COMPLETE = '0', 1, 0) as tag, row_number() over (order by NAME) as rn
                  from b20210226
              ) t1
     ) t2
    ) t3
order by NAME,TIME;

265.文本处理

sql
CREATE TABLE c20210226 (地址 VARCHAR(100));

INSERT INTO c20210226 VALUES('北京市东城区273号201房');
INSERT INTO c20210226 VALUES('广州市天河区11号1311房');
INSERT INTO c20210226 VALUES('深圳市福田区992号121房');

把数字替换为*
.....有问题,怎么变成一行了,不知道怎么用正则写??

sql
SELECT regexp_replace(地址,'[0-9]','*')  FROM c20210226 ;

可以使用变量来解决

266.left join

sql
CREATE TABLE T0222B
(WAREHOUSE VARCHAR(10),
 ITEM VARCHAR(10),
 QTY INT
);

INSERT INTO T0222B VALUES ('A','P001',50);
INSERT INTO T0222B VALUES ('B','P001',30);

CREATE TABLE T0222C
(WAREHOUSE VARCHAR(10),
 ITEM VARCHAR(10),
 QTY INT
);

INSERT INTO T0222C VALUES ('A','P001',10);
INSERT INTO T0222C VALUES ('A','P002',20);
INSERT INTO T0222C VALUES ('C','P001',15);
INSERT INTO T0222C VALUES ('C','P003',10);

说明:
表1.仓库,产品,期初余额
表2.仓库,产品,发出金额
表3.仓库,产品,收入

求:仓库,产品的详情和期末余额

sql
select
t1.WAREHOUSE as '仓库',t1.ITEM as '产品',ifnull(t1.QTY,0) as '期初' , ifnull(t2.QTY,0) as '发出' ,ifnull(t3.QTY,0) as '收入' ,
       (ifnull(t1.QTY,0) - ifnull(t2.QTY,0) + ifnull(t3.QTY,0) ) as '结存'
from T0222A t1 left join T0222B  t2 on t1.WAREHOUSE = t2.WAREHOUSE and t1.ITEM = t2.ITEM
left join T0222C t3  on   t1.WAREHOUSE = t3.WAREHOUSE and t1.ITEM = t3.ITEM

union all

select
WAREHOUSE,ITEM,0,0,QTY,QTY
from T0222C
where (WAREHOUSE,ITEM) not in (select WAREHOUSE,ITEM from T0222A);

有full join 就用这个避免使用union all 连接子查询

267.循环

定义如下两个变量
DECLARE @date_start datetime
DECLARE @date_end datetime
set @date_start = '2021-02-20 01:00:00'
set @date_end = '2021-02-20 10:00:00'
希望求解出两个变量直接每小时的时间分布

学习一下时间相减函数

sql
select  TIMESTAMPDIFF(hour ,'2021-02-20 01:00:00','2021-02-20 10:00:00' ) ;

select datediff('2021-02-02','2021-01-09');

date_add('2021-02-20 01:00:00, interval 1  hour )

提供一种写法,可能跨年的时候不适用

sql
with   recursive x(number) as (
        select 0
        union  all
        select  number + 1 from x where  number <  (select  TIMESTAMPDIFF(hour ,'2021-02-20 01:00:00','2021-02-20 10:00:00' ))
    )

select
date_add(t1.times, interval number hour )
from  x cross join ( select '2021-02-20 01:00:00' as times ) t1 ;

268.指标

有一张充值表,先需要根据财务的需求,根据充值日期、有效天数和充值金额分摊到2020年最后一天,即2020年12月31日。

sql
CREATE TABLE T0218
(
订单号 VARCHAR(10),
充值日期 DATE,
充值金额 double,
充值产品 VARCHAR(100),
有效天数 INT
)
 
INSERT INTO T0218 VALUES('1001','2020-07-01',500.00,'初一数学提高班',90)
INSERT INTO T0218 VALUES('1002','2020-08-04',1000.00,'成人英语口语突破班',30)
INSERT INTO T0218 VALUES('1003','2020-09-10',2000.00,'初三数学提高班',240)
INSERT INTO T0218 VALUES('1004','2020-11-15',3000.00,'高三语文作文提高班',360)
INSERT INTO T0218 VALUES('1005','2020-12-20',2000.00,'高一物理精讲班',60)

在上表的基础上增加两列分摊金额和剩余金额。分摊金额时,包括充值日期和2020年12月31日这两天,即包括头尾日期。

例如2020-09-10这天充值了2000元,从2020-09-10到2020-12-31日这一天总共有113天,实际有效期为240天,那么到2020-12-31日这一天,需要分摊这2000元的金额计算方式为:2000/240*113=941.6629。如果有效天数小于到2020-12-31日这天的天数,那么就全部分摊

sql
select *,
       if(datediff('2020-12-31',t1.充值日期 ) >= t1.有效天数 , round(t1.充值金额,4) ,round(t1.充值金额 * datediff('2020-12-31',t1.充值日期 ) / t1.有效天数,4) ) as '分摊金额',
       if(datediff('2020-12-31',t1.充值日期 ) >= t1.有效天数 , 0.0000 ,round(t1.充值金额 -  t1.充值金额 * datediff('2020-12-31',t1.充值日期 ) / t1.有效天数,4)) as '剩余金额'
from T0218 t1;
sql
//优化一下,把if中的计算步骤放在里select,在外面嵌套一层select来求取

269.group by

sql
CREATE TABLE T0205A (
A VARCHAR(20),
B VARCHAR(20)
)

INSERT INTO T0205A VALUES('跑步','张三');
INSERT INTO T0205A VALUES('游泳','张三');
INSERT INTO T0205A VALUES('跳远','李四');
INSERT INTO T0205A VALUES('跳高','王五');

CREATE TABLE T0205B (
A VARCHAR(20),
B VARCHAR(20),
C VARCHAR(10)
)

INSERT INTO T0205B VALUES('跑步','张三','胜');
INSERT INTO T0205B VALUES('游泳','张三','胜');
INSERT INTO T0205B VALUES('跳高','王五','胜');

anum表示每个人参加的项目数,bnum表示每个人在各自项目中胜利的次数

text
       anum   bnum
张三	2	2
王五	1	1
李四	1	0
sql
select
t1.B,
       count(1) as anum,
       count(if(t2.C='胜',1,null)) as bnum
from T0205A t1  left join T0205B t2  on  t1.A = t2.A and t1.B = t2.B
group by  t1.B;

270.上下比较

sql
CREATE TABLE T0204 (
ID INT,
Num INT
);

INSERT INTO T0204 VALUES(1,5);
INSERT INTO T0204 VALUES(2,11);
INSERT INTO T0204 VALUES(3,0);
INSERT INTO T0204 VALUES(4,-2);
INSERT INTO T0204 VALUES(5,2);
INSERT INTO T0204 VALUES(6,9);
INSERT INTO T0204 VALUES(7,1);
INSERT INTO T0204 VALUES(8,-4);
INSERT INTO T0204 VALUES(9,-7);

当Num中的数据同时大于上下两行数据,返回是
当Num中的数据小于上下两行数据中的任何一行,返回否

例如:11大于5,11大于0,所以返回是
5小于11所以返回否

注意学习窗口中控制大小的用法

sql
select *,
case when max(Num) over ( order by id  rows between 1 preceding  and  1 following ) <= Num  then '是' else '否'end
from T0204;

方法二可以使用偏移量函数的上移和下移

sql
select *,
case when lag(Num) over (order by ID) < Num AND LEAD(Num) over (order by ID) < Num then '是' else '否'end
from T0204;

练习题 23:每月十题(二)

271.九九乘法表

要求:打印九九乘法表

sql
with recursive t(n) as (
      select  1
      union  all
      select  n + 1 from t where  n < 9
)

select
group_concat(n order  by n separator ' ')
from (
         select left_n,
                concat_ws('=', concat_ws('*', left_n, right_n), result) as n
         from (
                  select t1.n        as left_n,
                         t2.n        as right_n,
                         t1.n * t2.n as result
                  from t t1
                           join t t2 on t1.n >= t2.n
              ) s1
     ) s2
group by  left_n;

在hive中使用sort_array来排序

提供另一种方法

sql
with recursive t(n) as (
      select  1
      union  all
      select  n + 1 from t where  n < 9
)

select
max(if(right_n =1,result,'')),
       max(if(right_n =2,result,'')),
       max(if(right_n =3,result,'')),
       max(if(right_n =4,result,'')),
       max(if(right_n =5,result,'')),
       max(if(right_n =6,result,'')),
       max(if(right_n =7,result,'')),
       max(if(right_n =8,result,'')),
       max(if(right_n =9,result,''))
from (
         select t1.n as                                   left_n,
                t2.n as                                   right_n,
                concat(t2.n, '*', t1.n, '=', t1.n * t2.n) result
         from t t1
                  join t t2 on t1.n >= t2.n
     ) s1
group by left_n;

关于如何生成1-9的自然数,有方法row_number直接生成,变量生成,mysql的递归,直接union all 来生成

272.递归表达式和斐波那契数列

递归表达式的作用
生成斐波那契数列
补全两个日期之间的缺失日期;
树形查询

生成斐波那契数列

sql
with  recursive  t(id,first,last) as (
      select 1 as id ,
             1 as first,
             1 as last
             union  all
     select  id +1 ,
             if(id< 2 ,1 ,first + last),
             first

     from t
     where  id < 10
)

select first  from  t;

273.5X5方格棋盘难题

在5X5的方格棋盘中(如图),每行、列、斜线(斜线不仅仅包括对角线)最多可以放两个球,如何摆放才能放置最多的球,这样的摆法总共有几种?输出所有的摆法。
要求:用一句SQL实现

http://www.itpub.net/thread-1407072-1-1.html
有兴趣的学习一下,这是第一届的题目

274.行转列问题

现有一表数据如下

text
设备  加油量    加油日期
A1     10       2012-10-1

A2     2        2012-10-2

A3     3        2012-10-1

现在想得到10月份每天每台设备的加油汇总表,如下

text
A1	10	10	10	10	10	10
A2	0	3	3	3	3	3
A3	0	0	5	9	9	9
      10	13	18	22	22	22
sql
create table if not exists cheer(
       equipment  varchar(2),
       fuel_charge  double,
      fuel_datetime  date
);

insert into cheer values ('A1',10,'2021-10-1');
insert into cheer values ('A2',3,'2021-10-2');
insert into cheer values ('A3',5,'2021-10-3');
insert into cheer values ('A3',4,'2021-10-4');

也不是什么正规的行转列,提供一种写法

sql
with x as (
    select equipment,
           sum(if(fuel_datetime <= '2021-10-01', charge, 0)) as '1',
           sum(if(fuel_datetime <= '2021-10-02', charge, 0)) as '2',
           sum(if(fuel_datetime <= '2021-10-03', charge, 0)) as '3',
           sum(if(fuel_datetime <= '2021-10-04', charge, 0)) as '4',
           sum(if(fuel_datetime <= '2021-10-04', charge, 0)) as '5',
           sum(if(fuel_datetime <= '2021-10-04', charge, 0)) as '6'
    from (
             select equipment,
                    fuel_datetime,
                    sum(fuel_charge) as charge
             from cheer
             where fuel_datetime like '2021-10%'
             group by equipment, fuel_datetime
         ) t1
    group by equipment
)
select  * from x
union  all
select
group_concat(equipment),sum(x.`1`),sum(x.`2`),sum(x.`3`),sum(x.`4`),sum(x.`5`),sum(x.`6`)
from x ;

发现这种写法不符合题意使用打标签的方法来统计

sql
select
equipment,
           sum(if(fuel_datetime = '2021-10-01', charge, 0)) as '1',
           sum(if(fuel_datetime = '2021-10-02', charge, 0)) as '2',
           sum(if(fuel_datetime = '2021-10-03', charge, 0)) as '3',
           sum(if(fuel_datetime = '2021-10-04', charge, 0)) as '4',
           sum(if(fuel_datetime = '2021-10-05', charge, 0)) as '5',
           sum(if(fuel_datetime = '2021-10-06', charge, 0)) as '6',
           sum(charge) as '1-31'
from (
         select 1 as 'type', cheer.equipment, cheer.fuel_charge as charge , cheer.fuel_datetime
         from cheer where fuel_datetime like '2021-10%'

         union all

         select 2 as 'type', '日统计' , sum(fuel_charge), fuel_datetime
         from cheer
         where
         fuel_datetime like '2021-10%'
         group by fuel_datetime
     ) t1
group by type,equipment;

275.混合排序

有点难度....
示例

name 是店铺名称,名称中带有“-”表示分店,score 是销售额。出题人希望能依据城市、销售额查看各个店铺的销售数据,并且当存在分店时,分店能紧挨在总店后面按照 id 排序

sql
create table order_data (
     id int ,
     city varchar(1),
     name  varchar(4),
     score int
);

insert into order_data values (1,'a','A',100);
insert into order_data values (2,'a','A-1',80);
insert into order_data values (3,'b','C',70);
insert into order_data values (4,'a','A-2',90);
insert into order_data values (5,'b','D',85);
insert into order_data values (6,'b','B',75);
insert into order_data values (7,'b','E',30);
insert into order_data values (8,'b','B-1',50);
insert into order_data values (9,'a','F',95);
insert into order_data values (10,'b','G',65);

非常巧妙,提供一种方法

sql
with  x as (
     select
     id, city, name, score,
           if( instr(name,'-'),substr(name,1,1),name  ) as base_name
     from order_data
)

select
x.id,x.city,x.name,
x.score
from order_data join x  on  order_data.name  = x.base_name
order by x.city,order_data.score desc,x.id;

276.获取状态一致的分组

简单题
星星点灯是一家水果店,它提供了外卖水果拼盘的服务。水果店能够提供四种水果拼盘:水果魔方、海星欧蕾、猫头鹰、草莓雪山,下表反应了某一时刻店内的水果的准备情况。

sql
create  table  if not exists fruit_data (
       id int,
       platter  varchar(6),
       fruit    varchar(6),
       ready    int
);
insert into fruit_data values (1,'水果魔方','猕猴桃',1);
insert into fruit_data values (2,'水果魔方','香蕉',1);
insert into fruit_data values (3,'水果魔方','菠萝',1);
insert into fruit_data values (4,'水果魔方','芒果',1);
insert into fruit_data values (5,'水果魔方','哈密瓜',1);
insert into fruit_data values (6,'水果魔方','猕猴桃',1);
insert into fruit_data values (7,'海星欧蕾','草莓',0);
insert into fruit_data values (8,'海星欧蕾','橙子',1);
insert into fruit_data values (9,'猫头鹰 ','猕猴桃',1);
insert into fruit_data values (10,'猫头鹰 ','小橙子',1);
insert into fruit_data values (11,'猫头鹰 ','橘子',1);

上面这些数据存在 platters 表中,platter 是拼盘的名称,fruit 是拼盘要用到的水果,ready 表示水果是否准备好了。当有客户订水果拼盘时,只有拼盘要用到的所有水果都准备好了才能制作。
现在,我们要写 SQL 找出可以立即制作的水果拼盘的名称。

sql
select
fruit_data.platter
from fruit_data
group by platter
having sum(if(ready=1,0,1)) =0 ;

select
fruit_data.platter
from fruit_data
group by platter
having sum(if(ready=1,1,0)) = count(*);

select distinct platter
from fruit_data
where platter not in (
select
platter
from fruit_data
where ready =0 ) ;

277.mysql中的更新语法

更新语法没怎么用过,学习一下

sql
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET assignment_list
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

你会发现有limit 和 order by 语法,实践一下

sql
create  table  update_test (
     id int ,
     test0 int ,
     test1 int ,
     test2 int
);

insert into update_test values (1,1,1,1);
insert into update_test values (2,1,1,1);
insert into update_test values (3,1,1,1);
insert into update_test values (4,1,1,1);
insert into update_test values (5,1,1,1);
sql
update  update_test
set test0 =2
limit 2;

update  update_test
set test1 =2
order by  id desc
limit 2;

update  update_test
set
    test1 =10 * test0,
    test2 = test1
limit 2;

不过,需要注意的是,如果更新的行的原来的值和要更新的值一致,那么 MySQL 并不会真正执行更新操作,但仍会计入受 LIMIT 子句影响的行数。

注意update和子查询的结合的注意事项

ERROR 1093 (HY000): You can't specify target table 'xxx' for update in FROM clause

278.最短路径

从出发地到目的地有多条路线可走,要求使用算法找出最短路径。
如果使用的是 SQL ,怎么解决这类问题?

text
sp      ep      distance  
------  ------  ----------
a       b                5
a       c                1
b       c                2
b       d                1
c       d                4
c       e                8
d       e                3
d       f                6
sql
create table max_data (
     sp varchar(1),
     ep varchar(1),
     distance int
);
insert into max_data values ('a','b',5);
insert into max_data values ('a','c',1);
insert into max_data values ('b','c',2);
insert into max_data values ('b','d',1);
insert into max_data values ('c','d',4);
insert into max_data values ('c','e',8);
insert into max_data values ('d','e',3);
insert into max_data values ('d','f',6);

递归的思路:
先获取与a的直接间接(目前有 a -> b、a -> c 这两条路线。),与原表join,条件是 t 表的ep = 原表的sp,获取原表的ep

在 SQL 中加入了条件 INSTR(t.path, b.ep) <= 0 , 主要是防止有环路而出现死循环

sql
with  recursive  t(sp,ep,distance,path) as (
      select * ,cast(concat(sp,'-->',ep) as CHAR(100)) as path   from max_data where sp = 'a'

      union  all
      select
      t.sp ,t1.ep,t1.distance + t.distance ,cast(concat(t.path ,'-->',t1.ep) as CHAR(100)) as path
      from t
          join max_data t1 on  t.ep = t1.sp and instr(t.path , t1.ep) <= 0
)

select sp,ep,distance,path
from  (
select  * ,row_number() over (partition by ep  order by  distance) as rn
from t ) t1
where rn =1;

279.背包问题

这是一道简化的背包问题:有一背包能容纳 50kg 的物品,现有 9 种物品(它们的重量分别是 5kg、8kg、20kg、35kg、41kg、2kg、15kg、10kg、9kg),要刚好能装满背包,有多少种物品组合?

sql
create  table if not exists  knapsack (
     id int ,
     weight int
);

insert into  knapsack values (1,5);
insert into  knapsack values (2,8);
insert into  knapsack values (3,20);
insert into  knapsack values (4,35);
insert into  knapsack values (5,41);
insert into  knapsack values (6,2);
insert into  knapsack values (7,15);
insert into  knapsack values (8,10);
insert into  knapsack values (9,9);

提供一种写法,递归来做

sql
with recursive  t(first_id,count_num,id_path,num_path,next_id) as (
       select
       id as fistst_id,
       weight as count_num,
       cast(id as char(100)) as id_path,
       cast( weight as char(100)) as num_path ,
       id as next_id
       from knapsack

    union  all

    select
    t.first_id,
    t.count_num + t1.weight,
    cast( concat(t.id_path ,'--',t1.id) as char(100))  ,
    cast( concat(t.num_path,'--',t1.weight) as char(100)) ,
    t1.id
    from knapsack t1 ,t
    where t.next_id < t1.id and t.count_num + t1.weight <= 50
)
select  * from t  where count_num = 50 ;

做了三道递归,发现自连接有妙用啊,学习一下

280.分析大盘走势

下表(stock)记录了某指数过去一段时间的收盘价,我们要从这张表中找出收盘价持续上涨的日期

希望得到的结果

text
2020-11-24----2020-11-26	3362	3408
2020-11-27----2020-11-30	3391	3451
text
create  table  grail (
    deal_date date,
    price   double
);

insert  into grail values ('2020-11-20',3424);
insert  into grail values ('2020-11-23',3402);
insert  into grail values ('2020-11-24',3362);
insert  into grail values ('2020-11-25',3369);
insert  into grail values ('2020-11-26',3408);
insert  into grail values ('2020-11-27',3391);
insert  into grail values ('2020-11-30',3451);
insert  into grail values ('2020-12-01',3449);
insert  into grail values ('2020-12-02',3441);
sql
select
concat(min(deal_date),'----',max(deal_date)),
       min(price),
       max(price)
from (
         select deal_date,
                price,
                sum(lag_p) over (order by deal_date) as lag_s
         from (
                  select *,
                         if(price - lag(price, 1, price) over (order by deal_date) <= 0, 1, 0) as lag_p
                  from grail
              ) t1
     ) t1
group by  lag_s
having count(1) >= 2;

和前面的穿鞋子那题一个套路,打标签,注意lag/lead拉取比较时的变化
另一种方法是求取所有的时间组合然后进行比较

练习题 24:每月十题(三)

281.获取定长连续子序列

sql
create table savior (
     id int , status int
);

insert  into savior values (1,1);
insert  into savior values (2,1);
insert  into savior values (3,0);
insert  into savior values (4,0);
insert  into savior values (5,0);
insert  into savior values (6,1);
insert  into savior values (7,0);
insert  into savior values (8,0);
insert  into savior values (9,0);
insert  into savior values (10,0);
insert  into savior values (11,0);
insert  into savior values (12,1);
insert  into savior values (13,1);
insert  into savior values (14,0);
insert  into savior values (15,0);

要求:从 savior 表中获取状态为 0 的 id,并且这些 id 能够组成长度为 3 的连续子序列。

text
3~5     
7~9     
8~10    
9~11   

提供一种写法,这种题目在上一篇中有类似的题目,发现最后一行是不符合题意的,怎么有效率过滤掉是难题....想不到确实不好求....

sql
select
concat(id-1,'---',id+1)
from (
         select id,
                status,
                max(status) over (order by id rows between 1 preceding and 1 following ) as max_number
         from savior
     ) t1
where  max_number =0 ;

方法二:使用自连接也可以求取,答案提供的是row_number获取重复的便签,使用自连接来获取连续的值

sql
WITH cte AS 
(SELECT 
  *,
  row_number() over (
ORDER BY id) AS rn 
FROM
  savior 
WHERE STATUS = 0) 
SELECT 
  CONCAT_WS('~', a.id, b.id) AS subseq 
FROM
  cte a 
  INNER JOIN cte b 
    ON a.id + 2 = b.id 
    AND a.rn + 2 = b.rn 

方法三.使用偏移量函数来求取
学习一下max()等窗口函数嵌套if等,到底判断的是什么???例如

sql
   select id,
                status,
                max(if(status = 1  , 5,status)) over (order by id rows between 1 preceding and 1 following ) as max_number
         from savior

只要max中有一个数是满足的那么结果就是5,!!!!!!

282.动态规划

有100天的商品价格,按照买入卖出的顺序,怎么操作能赚得最多的价值,以及是多少

sql
create table dtgh (
        data int
);
insert into dtgh values (1);
insert into dtgh values (3);
insert into dtgh values (4);
insert into dtgh values (10);
insert into dtgh values (9);
insert into dtgh values (7);
insert into dtgh values (12);
insert into dtgh values (1);
insert into dtgh values (2);
insert into dtgh values (1);
insert into dtgh values (1);

这是一道动态规划题,使用SQL怎么写

sql
select
concat(min(data),',',max(data)) ,max(data) - min(data)
from (
         select data,
                sum(`lag`) over (order by rn ) as money
         from (
                  select data,
                         if(data - num < 0, 1, 0) as `lag`,
                         row_number() over ()     as rn
                  from (
                           select data,
                                  lag(data, 1, data + 1) over () as num
                           from dtgh
                       ) t1
              ) t2
     ) t3
group by money
having count(1) > 1 and ( max(data) - min(data) > 0  );

283.层级查询(一)

在工作中都遇到过存在层次关系的数据表,典型的例子诸如菜单表(多级菜单)、用户表(拥有上下级关系)、商品类目表(多级类目)

text
 empno  ename      mgr  
------  ------  --------
  7369  SMITH       7902
  7499  ALLEN       7698
  7521  WARD        7698
  7566  JONES       7839
  7654  MARTIN      7698
  7698  BLAKE       7839
  7782  CLARK       7839
  7788  SCOTT       7566
  7839  KING      (NULL)
  7844  TURNER      7698
  7876  ADAMS       7788
  7900  JAMES       7698
  7902  FORD        7566
  7934  MILLER      7782

其中,mgr 为 NULL 表明该员工没有上级领导。
我们要把每个员工的所有上级领导都找出来,实现的效果如下:

text
 empno  ename   path                  
------  ------  ----------------------
  7369  SMITH   ->FORD->JONES->KING   
  7499  ALLEN   ->BLAKE->KING         
  7521  WARD    ->BLAKE->KING         
  7566  JONES   ->KING                
  7654  MARTIN  ->BLAKE->KING         
  7698  BLAKE   ->KING                
  7782  CLARK   ->KING                
  7788  SCOTT   ->JONES->KING         
  7839  KING                          
  7844  TURNER  ->BLAKE->KING         
  7876  ADAMS   ->SCOTT->JONES->KING  
  7900  JAMES   ->BLAKE->KING         
  7902  FORD    ->JONES->KING         
  7934  MILLER  ->CLARK->KING    

对于编号为 7369 的 SMITH,他的直属领导的编号是 7902,姓名叫做 FORD;FORD 的直属领导叫做 JONES,编号为 7566;编号为 7566 的直属领导是编号为 7839 的 KING,而 KING 没有直属领导。因此,SMITH 的上级领导的关系链构成:->FORD->JONES->KING

sql
WITH RECURSIVE leader_path(empno, ename, mgr, path) AS 
(SELECT 
  empno,
  ename,
  mgr,
  CAST('' AS CHAR(100)) AS path 
FROM
  emp 
UNION ALL 
SELECT 
  a.empno,
  a.ename,
  b.mgr,
  CONCAT(
    a.path,
    IFNULL(CONCAT('->', b.ename), '')
  ) 
FROM
  leader_path a 
  LEFT JOIN emp b 
    ON a.mgr = b.empno 
WHERE b.empno IS NOT NULL) 
SELECT 
  empno,
  ename,
  path 
FROM
  leader_path 
WHERE mgr IS NULL 
ORDER BY 1 

在递归中一定要加入终止条件,本 SQL 的终止条件是 WHERE b.empno IS NOT NULL;
遇到字符串拼接需要提前设置该字段的长度,对应到 SQL 中的操作是 CAST('' AS CHAR(100));
递归会生成中间结果,我们要把中间结果过滤掉,WHERE mgr IS NULL 就是只获取最终的结果。

284.层级查询(二)

在mysql中实现层次查询的两种方式。层级查询(一)举的示例是获取从叶子点到根节点的路径,层级查询(二)要实现的是从根节点找到所有叶子节点。

sql
WITH RECURSIVE leader_path (empno, ename, mgr, lv) AS 
(SELECT 
  empno,
  ename,
  mgr,
  1 AS lv
FROM
  emp WHERE mgr IS NULL
UNION ALL 
SELECT 
  b.empno,
  b.ename,
  b.mgr,
  lv + 1
FROM
  leader_path a 
  INNER JOIN emp b 
    ON a.empno = b.mgr ) 
SELECT 
  empno,
  ename,
  lv 
FROM
  leader_path 
ORDER BY 1 

结果如下:

text
 empno  ename       lv  
------  ------  --------
  7369  SMITH          4
  7499  ALLEN          3
  7521  WARD           3
  7566  JONES          2
  7654  MARTIN         3
  7698  BLAKE          2
  7782  CLARK          2
  7788  SCOTT          3
  7839  KING           1
  7844  TURNER         3
  7876  ADAMS          4
  7900  JAMES          3
  7902  FORD           3
  7934  MILLER         3

285.获取一行中多个字段的最大值

text
    id      v1      v2      v3  
------  ------  ------  --------
     1     100      80       102
     2       2     -20        -1
     3     999      12       111
     4    1234    2222      -123
     5     871     888       666
     6    -210       9      1024
     7       0      -1         0
     8       2       2         2

查询结果

text
    id   v_max  
------  --------
     1       102
     2         2
     3       999
     4      2222
     5       888
     6      1024
     7         0
     8         2

方法一:GREATEST()函数

sql
SELECT 
  id,
  GREATEST(v1, v2, v3) AS v_max 
FROM
  chaos

方法二:嵌套的 IF 语句

text
v12 = IF(v1 > v2, v1, v2)
v_max = IF(v12 > v3, v12, v3)

即:

sql
--有点复杂.....
SELECT 
  id,
  IF(
    IF(v1 > v2, v1, v2) > v3,
    IF(v1 > v2, v1, v2),
    v3
  ) AS v_max 
FROM
  chaos

方法三:使用union all 扁平化

sql
WITH chaos_union AS 
(SELECT 
  id,
  v1 AS v 
FROM
  chaos 
UNION ALL 
SELECT 
  id,
  v2 AS v 
FROM
  chaos 
UNION ALL 
SELECT 
  id,
  v3 AS v 
FROM
  chaos)
SELECT 
  id,
  MAX(v) AS v_max 
FROM
  chaos_union 
GROUP BY id 

286.分位函数

hive中求中位数,我一般是用正序和逆序来解决,这里提供hive中的分位函数来求取中位数

https://blog.csdn.net/Jarry_cm/article/details/82185576?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161631858216780265426998%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=161631858216780265426998&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~

percentile:percentile(col, p) col是要计算的列(值必须为int类型),p的取值为0-1,若为0.2,那么就是2分位数,依次类推。
percentile_approx:percentile_approx(col, p)。列为数值类型都可以。
percentile_approx还有一种形式percentile_approx(col, p,B),参数B控制内存消耗的近似精度,B越大,结果的精度越高。默认值为10000。当col字段中的distinct值的个数小于B时,结果就为准确的百分位数

287.打标签(1)

下面两题是携程数仓的面试题

sql
create table if not exists  xiechen  (
     time_day  date,product varchar(4) ,profit int
);

insert into xiechen values ('2021-01-01','A',2);

insert into xiechen values ('2021-01-02','A',3);
insert into xiechen values ('2021-01-03','A',4);
insert into xiechen values ('2021-01-04','A',5);
insert into xiechen values ('2021-01-01','B',2);
insert into xiechen values ('2021-01-02','B',4);
insert into xiechen values ('2021-01-03','B',3);
insert into xiechen values ('2021-01-04','B',4);
insert into xiechen values ('2021-01-01','B',5);

求每组收益连续增加3天以上的天数

sql
select concat(min(time_day),'--',max(time_day)) , max(product)
from (
         select time_day,
                product,
                profit,
                sum(lag_rn) over (partition by product order by time_day) as rn
         from (
                  select time_day,
                         product,
                         profit,
                         if(profit - lag(profit, 1, profit) over (partition by product) <= 0, 1, 0) as lag_rn
                  from xiechen) t1
     )  t2
  group by product,rn
  having  count(rn) >= 3;

288.打标签(2)

题目:在第一题的基础上,求日期是连续的且收益是连续3天递增的
解答:
在第一题的基础上在group by 后的having后增加:having count(rn) >= 3 and datediff(max(time_day),min(time_day)) + 1 = count(rn);
只要datediff(max(time_day),min(time_day)) 间隔数等于总的行数就是答案

sql
select concat(min(time_day),'--',max(time_day)) , max(product)
from (
         select time_day,
                product,
                profit,
                sum(lag_rn) over (partition by product order by time_day) as rn
         from (
                  select time_day,
                         product,
                         profit,
                         if(profit - lag(profit, 1, profit) over (partition by product) <= 0, 1, 0) as lag_rn
                  from xiechen) t1
     )  t2
  group by product,rn
  having  count(rn) >= 3 and datediff(max(time_day),min(time_day)) + 1 = count(rn);

289.魔力猫盒面试题

主粮,渴望,0.45
主粮,哈根纽翠斯,0.15
主粮,爱肯纳,0.40
罐头,仪亲,0.05
罐头,麦克劳德医生,0.8
罐头,happy100,0.15
零食,仪亲,0.24
零食,益智选,0.33
零食,mikbone,0.20
零食,巅峰,0.23

要求:求取amount_percent从大到小,累计和大于等于75%,的情况,且以大于等于75%为界限

sql
select cat_name,brand_name,amount_percent from(
   select
   cat_name,brand_name,amount_percent,calculate_percent,
   lag(calculate_percent,1,0) over(partition by cat_name order by calculate_percent) as lag_persent
   from
        (
         select
         cat_name,brand_name,amount_percent,
         sum(amount_percent) over(partition by cat_name order by amount_percent desc) as calculate_percent    
         from group_precent_top_n) as a1
      ) as a2
where (calculate_percent >= 0.75 and lag_persent < 0.75) or
(calculate_percent < 0.75 and lag_persent < 0.75)
;

其实不必这么写,这道题考查是沟通需求,过滤出特殊的数据行或者改写需求
提供其他方法:

  1. 使用hive中的桶函数分20个桶
  2. 如上面的解答方法使用sum窗口来求
  3. 使用row_number() 和count() 窗口来求
  4. 使用自连接来求

290.简单用户画像

有表sale:order_id 订单id,唯一字段 user_id 用户id product_id 订单id create_time 订单的创建时间 ,product_num 订单数
有表user_info user_id 用户id sex age

求:使用一条SQL生成完整的用户画像包含,用户id sex age d7order_num d14_order_num.后面两个字段分别为近七天的订单数,近14天的订单数

使用sum(if)来写

sql
select t1.user_id ,
       sex,
       age,
       sum(if(datediff('2021-3-21',create_time)<=7,product_num,0)) as d7order_num ,
       sum(if(datediff('2021-3-21',create_time)<=14,product_num,0)) as d14order_num
from user_info t1 left join sale t2 on t1.user_id = t2.user_id
group by t1.user_id, sex, age;

使用join来写

sql
select t1.user_id,sex,age,t2.d14order_num,t3.d7order_num
from user_info t1 left join (
      select  user_id ,sum(product_num) as d14order_num
             from sale
             where datediff('2021-3-21',create_time)<=14
             group by user_id
    ) t2 on t1.user_id = t2.user_id
left join (
        select  user_id ,sum(product_num) as d7order_num
              from sale
              where datediff('2021-3-21',create_time)<= 7
              group by user_id
    ) t3 on t1.user_id = t3.user_id;

练习题 25:每月十题(四)

291.数据补充

sql
create table null_attribution_lag(
stock_id string,
date_cal string,
price double
)
row format delimited fields terminated by ",";

data

300121,2020-10-01,10.65
300121,2020-10-02,11.65
300121,2020-10-03,12.15
300121,2020-10-04,10.00
300121,2020-10-05,10.99
300121,2020-10-06,
300121,2020-10-07,
300121,2020-10-08,10.01
300125,2020-10-01,8.65
300125,2020-10-02,9.65
300125,2020-10-03,9.11
300125,2020-10-04,
300125,2020-10-05,8.34
300125,2020-10-06,
300125,2020-10-07,
300125,2020-10-08,10.65

load data local inpath "/root/practice_data/null_attribution_lag" into table null_attribution_lag;

得到如下结果,如果为null则price为上面的不为null的那个值

+-----------+-------------+--------+------------+
| stock_id  |  date_cal   | price  | price_new  |
+-----------+-------------+--------+------------+
| 300121    | 2020-10-01  | 10.65  | 10.65      |
| 300121    | 2020-10-02  | 11.65  | 11.65      |
| 300121    | 2020-10-03  | 12.15  | 12.15      |
| 300121    | 2020-10-04  | 10.0   | 10.0       |
| 300121    | 2020-10-05  | 10.99  | 10.99      |
| 300121    | 2020-10-06  | NULL   | 10.99      |
| 300121    | 2020-10-07  | NULL   | 10.99      |
| 300121    | 2020-10-08  | 10.01  | 10.01      |
| 300125    | 2020-10-01  | 8.65   | 8.65       |
| 300125    | 2020-10-02  | 9.65   | 9.65       |
| 300125    | 2020-10-03  | 9.11   | 9.11       |
| 300125    | 2020-10-04  | NULL   | 9.11       |
| 300125    | 2020-10-05  | 8.34   | 8.34       |
| 300125    | 2020-10-06  | NULL   | 8.34       |
| 300125    | 2020-10-07  | NULL   | 8.34       |
| 300125    | 2020-10-08  | 10.65  | 10.65      |
+-----------+-------------+--------+------------+
sql

select stock_id,date_cal,price,max(price) over(partition by stock_id,sum_lable  order by date_cal) as price_new from(
    select stock_id,date_cal,price,
    sum(lable_price) over(partition by stock_id order by date_cal) as sum_lable
    from
         (select 
         stock_id,date_cal,price,if(price is null ,0,1) as lable_price
    from null_attribution_lag) as a1
    ) as a2;
sql
第二种方法:
通过lag或者lead函数,将null值滞后一项或者提前一项,将符合题意的分组在一起,再通过max函数进行补充数据
放弃:选择通过join的方式

如lag将滞后项与null放为一组

select
   stock_id,date_cal,lable_price,price,if(price is null or lag_price is null ,0,1) lable_01 
   from (
   select
   stock_id,date_cal,price,
   if(price is null ,0 ,1) as lable_price,
   lag(price,1,price) over(partition by stock_id  order by date_cal) as lag_price
   from null_attribution_lag
    ) as a1;

join的方式解决该类问题:

with a as (select
   stock_id,date_cal,price
from null_attribution_lag where price is null)
select * from a join null_attribution_lag on a.date_cal < null_attribution_lag.date_cal
and null_attribution_lag.price is not null
;

292.不用 UNION 操作符实现 UNION 的效果

sql

WITH a AS(
SELECT 1 AS id,'aaa' AS v
UNION ALL
SELECT 2 AS id,'bbb' AS v
UNION ALL
SELECT 2 AS id,'bbb' AS v
),b AS (
SELECT 1 AS id,'aaa' AS v
UNION ALL
SELECT 3 AS id,'ccc' AS v
)
select * from  a  union all  select * from  b ;

1	aaa
2	bbb
2	bbb
1	aaa
3	ccc

假设在结果集里已经存在 a 表的数据,现在要把 b 表的数据也加进来,使用left join来实现(打标签)

sql
WITH a AS(
SELECT 1 AS id,'aaa' AS v
UNION ALL
SELECT 2 AS id,'bbb' AS v
UNION ALL
SELECT 2 AS id,'bbb' AS v
),b AS (
SELECT 1 AS id,'aaa' AS v
UNION ALL
SELECT 3 AS id,'ccc' AS v
),c AS (
SELECT 0 AS flag
UNION ALL
SELECT 1 AS flag
)
select ifnull(a.id,b.id),ifnull(a.v,b.v) from c left join a on c.flag = 1 left join b on c.flag = 0 ;

要实现union 的效果直接group by 或者distinct即可

293.打印一个月的日历

sql
select day(curdate()); -- 这个月过了多少天
select date_add(curdate(),interval  - day(curdate()) + 1 DAY ); -- 月初
select last_day(curdate()); -- 月末

首先生成1-31天的id,用于生成这个月的所有天数(递归或者辅助表)

sql
with  recursive x(id) as (
    select 1 as id
    union all
    select id + 1 from x  where id < 31
    )
select
date_add(first_day , interval id - 1 DAY )
from (
    select date_add(curdate(),interval  - day(curdate()) + 1 DAY ) as first_day
                ) a ,x
where x.id <= day(last_day(curdate()));
sql
with  recursive x(id) as (
    select 1 as id
    union all
    select id + 1 from x  where id < 31
    )
    SELECT
  MAX(IF(wkday = 0, day_index, '')) AS '一',
  MAX(IF(wkday = 1, day_index, '')) AS '二',
  MAX(IF(wkday = 2, day_index, '')) AS '三',
  MAX(IF(wkday = 3, day_index, '')) AS '四',
  MAX(IF(wkday = 4, day_index, '')) AS '五',
  MAX(IF(wkday = 5, day_index, '')) AS '六',
  MAX(IF(wkday = 6, day_index, '')) AS '日'
FROM(
select
week(day_m,1) as wk ,
     weekday(day_m) as wkday,
     day(day_m) as day_index,
     day_m
from (
select
date_add(first_day , interval id - 1 DAY ) as day_m
from (
    select date_add(curdate(),interval  - day(curdate()) + 1 DAY ) as first_day
                ) a ,x
where x.id <= day(last_day(curdate())) ) b ) c group by wk  ;

294.确定序列里缺失值的范围

先来构造有缺失值的 seq 表,可以用 SQL 派生出这个表。

sql
WITH seq AS(
SELECT 1 AS id
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 5
UNION ALL SELECT 6
UNION ALL SELECT 7
UNION ALL SELECT 8
UNION ALL SELECT 12
UNION ALL SELECT 13
UNION ALL SELECT 15
UNION ALL SELECT 18
UNION ALL SELECT 19
UNION ALL SELECT 20
)

我们观察数据可知,seq 表中目前最大的数是 20,缺失的值有:4、9、10、11、14、16、17。

sql

SELECT
  START,
  STOP
FROM
  (SELECT
    s.id + 1 AS START,
    (SELECT
      MIN(id) - 1
    FROM
      seq AS xx
    WHERE xx.id > s.id) AS STOP
  FROM
    seq AS s
    LEFT JOIN seq AS r
      ON s.id = r.id - 1
  WHERE r.id IS NULL) AS t
WHERE STOP IS NOT NULL ;
sql
select id- 1 ,tag+1  from  (
SELECT id,lag(id,1,id) over () as tag from seq  ) t
where id - tag > 1;

295.打印矩阵 (一)

实现效果

text
A B C D E  F
1 2 3 4 5
6 7 8 9 10
..... 
  1. 排在同一行的数是因为它们本身除 5 后再向上取整得到的是同一个值;
  2. 排在同一列的数是因为它们本身对 5 求余的结果一致;
  3. 同一行的数从左到右是递增;同样,同一列的数从上到下也是递增的。
sql
WITH recursive t_seq (num) AS
(SELECT
  1 AS num
UNION
ALL
SELECT
  num + 1 AS num
FROM
  t_seq
WHERE num < 25),
x0 AS
(SELECT
  num,
  CEIL(num / 5) AS group_no
FROM
  t_seq),
x1 AS
(SELECT
  group_no AS row_no,
  MAX(IF(num % 5 = 1, num, NULL)) AS A,
  MAX(IF(num % 5 = 2, num, NULL)) AS B,
  MAX(IF(num % 5 = 3, num, NULL)) AS C,
  MAX(IF(num % 5 = 4, num, NULL)) AS D,
  MAX(IF(num % 5 = 0, num, NULL)) AS E
FROM
  x0
GROUP BY group_no)
SELECT A ,B ,C ,D ,E FROM x1 ;

296.打印矩阵 (二)

  1. 有一张 5 x 5 的表格,我们要往这张表格中填充 1~25 的数字;
  2. 如果是奇数行,则从左到右填充数字;如果是偶数行,就需要按从右到左的顺序填入数字。
  3. 先从表格的左上角(即第一行第一列)填入数字 “1”,在第一行第二列填入“2”,直到把第一行填满;
  4. 当上一行填满的时候,就开始往下一行填数据。比如,第二行要从右往左依次填入“6”、“7”、“8”、“9”、“10”。
  5. 循环反复,直到所有空格都填满数字。
sql
WITH recursive t_seq (num) AS
(SELECT
  1 AS num
UNION ALL
SELECT
  num + 1 AS num
FROM
  t_seq
WHERE num < 25),
     x0 AS
(SELECT
  num,
  CEIL(num / 5) AS group_no
FROM
  t_seq),
 x1 AS
(SELECT
  *,
  IF(group_no % 2 = 0, - 1 * num, num) AS ordered,
  row_number () over () AS seq
FROM
  x0
ORDER BY group_no,
  ordered),
 x2 AS
(SELECT
  group_no AS row_no,
  MAX(IF(seq % 5 = 1, num, NULL)) AS A,
  MAX(IF(seq % 5 = 2, num, NULL)) AS B,
  MAX(IF(seq % 5 = 3, num, NULL)) AS C,
  MAX(IF(seq % 5 = 4, num, NULL)) AS D,
  MAX(IF(seq % 5 = 0, num, NULL)) AS E
FROM
  x1
GROUP BY group_no)

SELECT
  A, B, C, D, E
FROM
  x2;

注意使用if(-)来重新排序的方法来转换序号的顺序

297.从字符串中提取数字

text
  id  v       
------  --------
     1  123     
     2  abc     
     3  1d3     
     4  0       
     5  123.0   
     6  0123    
     7  01#123  
     8  0$123   

希望得到如下结果

text
    id  v       mix     
------  ------  --------
     1  123     123     
     3  1d3     13      
     4  0       0       
     5  123.0   1230    
     6  0123    0123    
     7  01#123  01123   
     8  0$123   0123
sql
WITH RECURSIVE chaos (id, v, s, seq) AS 
(SELECT 
  id,
  v,
  SUBSTR(v, 1, 1) AS s,
  1 AS seq 
FROM
  mix 
UNION ALL 
SELECT 
  id,
  v,
  SUBSTR(v, seq + 1, 1),
  seq + 1 
FROM
  chaos 
WHERE seq <= CHAR_LENGTH(v) - 1) 

SELECT 
  id,
  v,
  GROUP_CONCAT(s 
    ORDER BY seq SEPARATOR '') AS mix 
FROM
  chaos 
WHERE s >= '0' 
  AND s <= '9' 
GROUP BY v,
  id 
ORDER BY id 
sql
SELECT 
  id,
  v,
  GROUP_CONCAT(s 
    ORDER BY seq SEPARATOR '') AS mix 
FROM
  (SELECT 
    mix.id AS id,
    v,
    SUBSTR(v, t20.id, 1) AS s,
    t20.id AS seq 
  FROM
    mix,
    t20 
  WHERE t20.id <= CHAR_LENGTH(v) 
  ORDER BY v,
    t20.id) t 
WHERE s >= '0' 
  AND s <= '9' 
GROUP BY v,
  id 
ORDER BY id 

298.统计奇数

统计ip每行奇数的个数

sql
use mydata;
CREATE TABLE T0416(
IP INT,
NUM1 INT,
NUM2 INT,
NUM3 INT
);
INSERT T0416
SELECT 1,3333,4442,221
UNION ALL
SELECT 2,65,24,96;

select * from T0416;
sql
select * ,NUM3%2 + NUM2%2 + NUM1%2 as '奇数'from T0416;

299.连续字符串

sql
CREATE TABLE T0414
(
    val VARCHAR(50)
);
insert into T0414(val) values('A10000003');
insert into T0414(val) values('A10000001');
insert into T0414(val) values('A10000002');
insert into T0414(val) values('A10000011');
insert into T0414(val) values('A10000004');
insert into T0414(val) values('A10000006');
insert into T0414(val) values('A10000009');
insert into T0414(val) values('A10000010');
insert into T0414(val) values('A10000012');

得到如下结果
A10000001-A10000004,A10000006,A10000009-A10000012

我写的有点复杂......

sql
with x as (
select val,sum(tag) over (order by val) as rang
from  (
select val,num,if (num - lag(num,1,num  ) over () = 1 ,0,1) as tag
from (
select val ,cast(substr(val,2)  as SIGNED ) as num  from  T0414 order by val ) a ) b )

select group_concat(nm) from (
select concat(min(val),'-',max(val)) as nm from x group by rang having  count(1) >1
union  all
select  min(val) from x group by rang having count(1) =1  order by nm ) t11 ;

300.机房状态(列转行)

sql
CREATE TABLE T0412A
(
ID INT,
机房 VARCHAR(20)
)
CREATE TABLE T0412B
(
ID INT,
机房ID INT,
主机名称 VARCHAR(20),
主机状态 INT
)
 
INSERT INTO T0412A VALUES (1,'机房A')
INSERT INTO T0412A VALUES (2,'机房B')
INSERT INTO T0412A VALUES (3,'机房C')
 
INSERT INTO T0412B VALUES (1,1,'主机A',1)
INSERT INTO T0412B VALUES (2,1,'主机B',1)
INSERT INTO T0412B VALUES (3,1,'主机C',2)
INSERT INTO T0412B VALUES (4,2,'主机D',0)
INSERT INTO T0412B VALUES (5,2,'主机E',1)

得到如下结果
机房 0 1  2
sql
select
a.机房,ifnull(sum(if(b.主机状态 = 0,1,0)),0) as '0',
       ifnull(sum(if(b.主机状态 = 1,1,0)),0) as '1',
       ifnull(sum(if(b.主机状态 = 2,1,0)),0) as '2'
from T0412A a left join T0412B b on a.ID = b.机房ID
group by a.机房;

此处主要回顾一下case when 和if语法,if语法不用说太多,注意一下if(负数)的用法即可还有count(null)...也就这些了,我经常混淆case when的用法这里简单地梳理一下

  1. 在group by中使用case when 是用来分类的,注意在select中也要有相同内容的case when
  2. case when 和 case .. when 无本质的区别,主要是是否复用值的区别,如下
text
CASE 字段 WHEN 值1 THEN 值1 [WHEN 值2 THEN 值2] [ELSE 值] END
CASE WHEN 条件表达式 THEN 值1 [WHEN 条件表达式 [and or] 条件表达式THEN 值2] [ELSE 值] END
  1. 在select中的case when 和if语法是一致的,如果参与聚合分类判断,则case when 就比if方便,主要也是用来分类的
  2. 在用于列转行/行转列的使用在case when 外面来嵌套一层聚合函数,用来分类,这里要注意一下细节

练习题 26:每月十题(五)

301.值班排表

sql
create table date_student (
     d  varchar(4)
);

create  table  if not exists  student1 (
     student varchar(5)
);

insert  into  date_student values ('0101'),('0102'),('0103'),('0104'),('0105'),('0106'),('0107');
insert  into  student1 values ('小明'),('小华'),('小红');
text
如上有日期和姓名表,要求依次组合生成一张排班表
0101	小明
0102	小华
0103	小红
0104	小明
0105	小华
0106	小红
0107	小明
sql
select d,student
from (
         select d, row_number() over () %3  as rn
         from date_student
     ) t1
join (
     select student,row_number() over () %3 as rw
     from student1
    ) t2
    on t1.rn  = t2.rw
order by d ;

302.TOP_N条件下计算最近14天趋势

SQL要求在kylin和presto中都能跑通

需求

有表test.table_0526
字段 常驻地resident_prov_name 人次person_num 时间 d
现在要求获取到上海的前20的客源地(按人次获取客源地),获取这些客源地最近14天的热度趋势(以用户输入的结束时间-14天为准,关于热度趋势的计算就是获取占比即可)

请求的区间必须大于14天,否则无法返回14天的趋势

sql
SELECT resident_prov_name, d, CAST(person_nums * 1.0 / SUM(person_nums) OVER (PARTITION BY resident_prov_name ) AS DECIMAL(9, 4)) AS ratio
FROM (
    SELECT resident_prov_name, d, person_nums
    FROM (
        SELECT resident_prov_name, d, person_nums, ROW_NUMBER() OVER (PARTITION BY resident_prov_name ORDER BY d DESC) AS rn
        FROM (
            SELECT resident_prov_name, d, person_nums
            FROM (
                SELECT resident_prov_name, d, person_nums, dense_rank() OVER (ORDER BY rw DESC) AS rn
                FROM (
                    SELECT resident_prov_name, d, person_nums, SUM(person_nums) OVER (PARTITION BY resident_prov_name ) AS rw
                    FROM (
                        SELECT resident_prov_name, d, SUM(person_num) AS person_nums
                        FROM  test.table_0526
                        WHERE d >= @startTime
                            AND d <= @endTime
                            AND to_country_name = @country
                            AND to_prov_name = @province
                            AND to_city_name = @city
                            AND resident_prov_name IS NOT NULL
                        GROUP BY resident_prov_name, d
                    ) a
                ) b
            ) c
            WHERE rn <= 20
        ) d
    ) e
WHERE rn <= 14
) f

如果用户请求的区间小于14天,也返还给用户14天的数据,怎么写(下面的这种写法查询一年的可以,但是时间区间过长kylin就报错了)

sql
SELECT resident_prov_name,
       d,
       CAST(person_nums * 1.0 / SUM(person_nums) OVER (PARTITION BY resident_prov_name) AS DECIMAL(9, 4)) AS ratio
FROM
  (SELECT resident_prov_name,
          d,
          SUM(person_num) AS person_nums,
          ROW_NUMBER() OVER (PARTITION BY resident_prov_name
                             ORDER BY d DESC) AS rn
   FROM test.table_0526
   WHERE d >= '2019-01-01'
     AND d <= @endTime
     AND to_country_name = @country
     AND to_prov_name = '上海'
     AND to_city_name = '上海'
     AND resident_prov_name IN
       (SELECT resident_prov_name
        FROM ctripdi_prodb.adm_order_allbu_share_day
        WHERE d >= @startTime
          AND d <= @endTime
          AND to_country_name = @country
          AND to_prov_name = @province
          AND to_city_name = @city
          AND resident_prov_name IS NOT NULL
        GROUP BY resident_prov_name
        ORDER BY SUM(person_num) DESC
        LIMIT 20)
   GROUP BY resident_prov_name,
            d) a
WHERE rn <= 14

303.同比计算

给定时间区间,对比去年相同区间,在top_20 view_spot_name中计算同比

sql
select view_spot_name,(lag_persons - persons) * 1.0 /persons as ratio
from
(
SELECT  view_spot_name,persons,LAG(persons,1) over(partition by view_spot_name order by lag1 ) as lag_persons
FROM (
(
   SELECT 1 as lag1,view_spot_name,sum(person_num) AS persons
   FROM test.table0527
   WHERE d >= '2020-05-01'
     AND d<='2021-05-10'
     AND to_country_name = '中国'
     AND to_prov_name = '上海'
     AND to_city_name = '上海'
     AND view_spot_name IS NOT NULL
   GROUP BY view_spot_name
   ORDER BY sum(person_num) DESC
   LIMIT 20
    )
     
    union all
    (
        SELECT 2,view_spot_name,sum(person_num)
        FROM test.table0527
        WHERE
            d >= concat(CAST(CAST(substring('2020-05-01', 1, 4) AS int) - 1 AS varchar), substring('2020-05-01', 5, 7))
            AND d <= concat(CAST(CAST(substring('2021-05-10', 1, 4) AS int) - 1 AS varchar), substring('2021-05-10', 5, 7))
            AND to_country_name = '中国'
            AND to_prov_name = '上海'
            AND to_city_name = '上海'
            AND view_spot_name IS NOT NULL
        GROUP BY view_spot_name
    )
    ) a 
    ) b  where lag_persons is not null

这里的问题是

text
concat(CAST(CAST(substring('2020-05-01', 1, 4) AS int) - 1 AS varchar), substring('2020-05-01', 5, 7))

不走rowkey,如果字段的枚举值过大就会无法执行,所以比较有效的方法是与前端沟通让他们传入时间
或者在底表先进行计算,改变粒度(之前的粒度为天,现在为月份)

另外kylin和presto的时间处理函数

text
kylin
TIMESTAMAPADD(DAY,-14,date '2021-01-01')

presto
date_add('day',-14,cast('2021-01-01' as date)
date_add('day',-14, date'2021-01-01' )

304.分区表批量补数

新建的一张分区表要补数,一般是一天一天的补数,但是这样比较麻烦,采用动态分区的方法来补数,效率将大大提升,set动态分区的参数,d>= 分区的初始时间,需要注意的是要先跑几个分区对比一下数据,当然这种动态分区补数的方法也是有缺陷的,动态分区的时间不是分区d就不能使用,因为可能其他的时间维度与分区不是一一对应的

如下一般的set参数

sql
set hive.merge.mapfiles=true;      --map端
set hive.merge.mapredfiles=true;       --reduce端
set hive.map.aggr=true;
SET hive.auto.convert.join=true;
SET hive.exec.max.dynamic.partitions.pernode=9000;
SET hive.exec.max.dynamic.partitions=9000;
set hive.exec.parallel=true;

306.TOP_20%条件下计算词频

有表test_table2,包含 master_hotel_name(酒店名称),,tag_name(评价词),
score(酒店评分),pplrt_num(评价词的词频)

现在的需求是要统计前20%酒店(按评分来排序)的评价词的词频
test_table2是我加工的表,来自于一张评价词词频表和酒店相关扩展表(包含酒店名称,评分等)

sql
SELECT tag_name as tag,sum(pplrt_nums) as pplrt_sum
FROM (
    SELECT master_hotel_name,tag_name,pplrt_nums, rn * 1.0 / counts AS a
    FROM (
        SELECT master_hotel_name,tag_name, score,pplrt_nums, ROW_NUMBER() OVER (ORDER BY score desc ) AS rn, COUNT(1) OVER () AS counts
        FROM (
            SELECT master_hotel_name,tag_name,SUM(score) as score ,SUM(pplrt_num) AS pplrt_nums
            FROM  test_table2
            WHERE d >=  '2021-05-27' and d <= '2021-05-27'
            GROUP BY master_hotel_id, master_hotel_name,tag_name
        )
    )
)
WHERE a <= 0.2 
group by tag_name
ORDER by pplrt_sum desc
LIMIT 50

307.每隔15min的记录数

sql
CREATE TABLE if not exists  test_0521(
ID INT ,
Times datetime
);

INSERT INTO test_0521
VALUES(1,'2021-05-24 11:01:45'),
      (2,'2021-05-24 11:03:15'),
      (3,'2021-05-24 11:05:34'),
      (4,'2021-05-24 11:09:23'),
      (5,'2021-05-24 11:17:45'),
      (6,'2021-05-24 11:19:15'),
      (7,'2021-05-24 11:29:34'),
      (8,'2021-05-24 11:37:23');
text
如何用SQL查询出每个15分钟的记录数,预期结果如下
2021-05-24 11:00:00,4
2021-05-24 11:15:00,3
2021-05-24 11:30:00,1

.....用mysql写着实有点复杂,这边的主要问题就是对时间的处理,不知道mysql有没有特定的时间处理函数集

sql
select
cast(concat(substr(date_add(date_sub( Times ,INTERVAL minute(Times) minute ),
INTERVAL floor(minute(Times) / 15) * 15  minute),1,17),'00') as datetime),
count(1)
from test_0521
group by 
cast(concat(substr(date_add(date_sub( Times ,INTERVAL minute(Times) minute ),
INTERVAL floor(minute(Times) / 15) * 15  minute),1,17),'00') as datetime);

我的思路如下,获取时间的分钟数与15进行比较,这样就正确处理了时间分钟,接着要对时间的秒进行处理,我这里是使用substr来切分concat来补充

308.时间段重叠取数问题

某直播业务会记录主播开播及关播时间。需要计算出每天的峰值及峰值出现时间。数据表如下,粒度为每秒

text
| user_id | start_time | end_time |
| ------- | ------------------- | ------------------- |
| 1 | 2020-01-07 01:03:01 | 2020-01-07 03:03:01 |
| 2 | 2020-01-07 01:05:01 | 2020-01-07 02:03:01 |
| 3 | 2020-01-07 01:09:01 | 2020-01-07 05:03:01 |
| 1 | 2020-01-07 09:10:01 | 2020-01-07 10:03:01 |

这道题主要考虑就是写一个循环,hive中提供了一个udaf函数,之前写过

sql
WITH a AS (
        SELECT '2021-04-20' AS depart_time, '2021-04-10' AS arrive_time
        UNION ALL
        SELECT '2021-03-11', '2021-03-09'
    )
SELECT pos
FROM a
    LATERAL VIEW POSEXPLODE(SPLIT(SPACE(DATEDIFF(TO_DATE(a.depart_time), TO_DATE(a.arrive_time)) - 1), ' ')) tf AS pos,val 

把时间转换为时间戳即可比较,然后在转过来

sql
select unix_timestamp('2020-09-15 10:35:33');
select from_unixtime(1000000000);

309.连续空余座位

sql
CREATE TABLE T0527
(
seat_id INT,
free INT
)

INSERT INTO T0527 VALUES 
(1,1),
(2,0),
(3,1),
(4,1),
(5,1)

seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。连续空余座位的定义是大于等于 2 个连续空余的座位
对于如上样例,你的查询语句应该返回如下结果。

text
3
4
5
sql
select seat_id
from (
         select SEAT_ID,
                FREE,
                LAG(free, 1, 0) over (ORDER BY seat_id)  AS LAG_1,
                LEAD(free, 1, 0) over (order by seat_id) as lead_1
         from T0527
     ) t1
where free <> 0 and (lead_1 =1 or LAG_1 =1 );
sql
select  seat_id
from (
         select seat_id,free,
                seat_id - lag(seat_id, 1) over (order by seat_id) as lag_1
         from T0527
     ) t1
where free<> 0 and lag_1 =1 ;

方法三可使用自连接判断abs

310.发货单号的最值

sql
CREATE TABLE T0520 
(
shipid INT,
paydate DATE,
payno INT
)

INSERT INTO T0520 VALUES(1001,'2020/11/2',5);
INSERT INTO T0520 VALUES(1001,'2020/11/2',3);
INSERT INTO T0520 VALUES(1001,'2020/11/3',1);
INSERT INTO T0520 VALUES(1001,'2020/11/3',3);
INSERT INTO T0520 VALUES(1002,'2020/11/9',1);
INSERT INTO T0520 VALUES(1002,'2020/11/9',4);
INSERT INTO T0520 VALUES(1002,'2020/11/8',3);
INSERT INTO T0520 VALUES(1002,'2020/11/8',2);

使用两种方法,查询出每个发货单号(shipid),最早付款时间(paydate)和最小付款单号(payno)

sql
select shipid, paydate, payno
from (
         select shipid,
                paydate,
                payno,
                row_number() over (partition by shipid order by paydate asc ,payno asc ) as rn
         from T0520
     ) t1
where  rn = 1;
sql
select a.shipid,a.paydate,min(a.payno)
from T0520 a
join (
    select shipid,min(paydate) as min_date
    from T0520
    group by shipid
    ) b on a.paydate = b.min_date and a.shipid = b.shipid
group by a.shipid,a.paydate;

练习题 27:每月十题(六)

311. 打标签合并

text
山西	交城	100	平安:40
山西	交城	100	非平安:60

合并成如下
山西	交城	100	平安:40  非平安:60
sql
create table a0628 (
    Secondaryinstitutions varchar(4) ,
    Tertiaryinstitutions   varchar(4),
    num int,
    sources varchar(10)
);
insert into a0628 values ('山西','交城',100,'平安:40'),('山西','交城',100,'非平安:60');
sql
select
Secondaryinstitutions, Tertiaryinstitutions, num,
       MAX(CASE  WHEN tag = '平安' then sources end) as '平安',
       MAX(CASE  WHEN tag = '非平安' then sources end) as '非平安'
from
     (
select
*,if ( left(sources,2)  = '平安' ,'平安' ,'非平安' ) as tag
from a0628 )  t1
group by Secondaryinstitutions,Tertiaryinstitutions,num;

312. explode()和posexplode()

参考文章
https://blog.csdn.net/dzysunshine/article/details/101110467?utm_medium=distribute.pc_relevant.none-task-blog-2~

1.-- explode的使用

select explode(split(concat_ws(',','1','2','3','4','5','6','7','8','9'),',')) ;

text
col
1 
2 
3 
4 
5 
6 
7 
8 
9 

关于explode的用法其实质上就是行转列,把一行转为多行
关于concat_ws的用法是第一个字段是分隔符,后split进行切分

2. -- LATERAL VIEW POSEXPLODE的使用
sql
WITH a AS (
        SELECT '2021-04-20' AS depart_time, '2021-04-10' AS arrive_time
        UNION ALL
        SELECT '2021-03-11', '2021-03-09'
    )
SELECT tf.*
FROM a
    LATERAL VIEW POSEXPLODE
 (SPLIT(SPACE(DATEDIFF(TO_DATE(a.depart_time), TO_DATE(a.arrive_time)) - 1), ' ')) tf 
3. -- LATERAL VIEW explode的使用(explode(array (or map))
  1. 示例一
sql
WITH x AS (
        SELECT 'a' AS id, '12_14_15' AS age
        UNION ALL
        SELECT 'b', '12_14_15'
    )
SELECT age_single
FROM x
    LATERAL VIEW explode(split(x.age, '_')) temp AS age_single
  1. 示例二,这里不使用with来展示,是由于这边的spark引擎不支持在with中使用array类型
sql
SELECT col
FROM (
    SELECT 'UU', array('A', 'B', 'C') AS arr
) t
    LATERAL VIEW explode(t.arr) tf AS col

3.示例三

sql
select t1.*,sp  from  (select 1 ) as t1    
lateral view explode(split(concat_ws(',','1','2','3','4','5','6','7','8','9'),',')) t as sp

这里本来是使用with的,但是发现可能是版本问题导致,所以我就使用嵌套一层select来处理了
4. 说明
lateral view explode() as temp 相当于生成了一张虚拟表,后与原表进行笛卡尔积
对于这两个UDTF函数的难点在于理解虚拟表的逻辑,以及在处理中使用正则表达式来获取正确的逻辑

参考文档,这里是SQL复杂处理的核心函数,掌握了这些就非常nice
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

313. 同比环比

如上,按月份聚合统计不同业务的同比/环比情况
这个SQL就是之前conf上写的SQL,这里复制一下,具体的看那篇博客即可

sql
select
lag,j_lag,
MAX(case when substring(j_month,6,7) = '01' then relative  end ) as m1,
MAX(case when substring(j_month,6,7) = '02' then relative  end ) as m2,
MAX(case when substring(j_month,6,7) = '03' then relative  end ) as m3,
MAX(case when substring(j_month,6,7) = '04' then relative  end ) as m4,
MAX(case when substring(j_month,6,7) = '05' then relative  end ) as m5,
MAX(case when substring(j_month,6,7) = '06' then relative  end ) as m6,
MAX(case when substring(j_month,6,7) = '07' then relative  end ) as m7,
MAX(case when substring(j_month,6,7) = '08' then relative  end ) as m8,
MAX(case when substring(j_month,6,7) = '09' then relative  end ) as m9,
MAX(case when substring(j_month,6,7) = '10' then relative  end ) as m10,
MAX(case when substring(j_month,6,7) = '11' then relative  end ) as m11,
MAX(case when substring(j_month,6,7) = '12' then relative  end ) as m12
from 
(
SELECT lag, '环比' AS j_lag, j_month
    , (order_price - lead_price_relative) * 1.0 / lead_price_relative AS relative
FROM (
    SELECT lag, j_month, order_price
        , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY j_month DESC) AS lead_price_relative
    FROM (
        SELECT concat(lag_country, bu) AS lag, j_month, order_price
        FROM (
            SELECT bu
                , CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END AS lag_country, substring(d, 0, 7) AS j_month
                , round(SUM(order_price), 0) AS order_price
            FROM table
            WHERE d >= '2019-01-01'
                AND bu IN ('机票', '酒店', '度假')
                AND d <> '4000-01-01'
            GROUP BY bu, substring(d, 0, 7), CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END
        ) a
    ) b
    WHERE lag IS NOT NULL
) c
UNION ALL
(
SELECT lag, '同比' , j_month
    , (order_price - lead_price_basis) * 1.0 / lead_price_basis 
FROM (
    SELECT lag, j_month, order_price
        , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY substring(j_month, 6, 7) DESC,substring(j_month, 0, 4) desc) AS lead_price_basis
    FROM (
        SELECT concat(lag_country, bu) AS lag, j_month, order_price
        FROM (
            SELECT bu
                , CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END AS lag_country, substring(d, 0, 7) AS j_month
                , round(SUM(order_price), 0) AS order_price
            FROM table
            WHERE d >= '2019-01-01'
                AND bu IN ('机票', '酒店', '度假')
                AND d <> '4000-01-01'
            GROUP BY bu, substring(d, 0, 7), CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END
        ) a
    ) b
    WHERE lag IS NOT NULL
) c
)
) 
WHERE substring(j_month, 0, 4) = '2021'
GROUP by lag,j_lag
order by substring(lag,3,4),substring(lag,0,2),j_lag

关于这道SQL主要用了如下知识点:标签,lead偏移,order by复合排序

314. 列转行

上边同比环比的超级简化版,简单复习一下列转行,注意max(case when的时候不要使用else null 可能会出问题)
对于行转列,事实上就是对数据结果的处理,而关于explode的用法其实质上就是行转列,把一行转为多行.

text
2020	1	9.1
2020	2	9.2
2020	3	9.3
2020	4	9.4
2021	1	8.1
2021	2	8.2
2021	3	8.3
2021	4	8.4

将如上转化为
year    M1   M2   M3   M4 
2020	9.1	9.2	9.3	9.4
2021	8.1	8.2	8.3	8.4
sql
create  table if not exists  b0628(
    year varchar(4), month varchar(1) ,amount double
);

INSERT INTO b0628 VALUES
('2020','1',9.1),
('2020','2',9.2),
('2020','3',9.3),
('2020','4',9.4),
('2021','1',8.1),
('2021','2',8.2),
('2021','3',8.3),
('2021','4',8.4);
sql
select
year,
        max(case  when month = 1 then amount end ) as M1,
        max(case  when month = 2 then amount end ) as M2,
        max(case  when month = 3 then amount end ) as M3,
        max(case  when month = 4 then amount end ) as M4
from b0628 group by year order by year ;

315. LAG&LEAD

偏移量函数的简单应用,写到这里我想起来了,sum等开窗函数可以限制窗口的大小,好久没用了

text
数据
id  NUM
1	5
2	11
3	0
4	-2
5	2
6	9
7	1
8	-4
9	-7

要求当NUM中的数同时大于上下两行数据,返回是,当num中的数据小于上下两行中的任意一行,返回否

sql
CREATE TABLE T0611 (
ID INT,
Num INT
);

INSERT INTO T0611 VALUES(1,5);
INSERT INTO T0611 VALUES(2,11);
INSERT INTO T0611 VALUES(3,0);
INSERT INTO T0611 VALUES(4,-2);
INSERT INTO T0611 VALUES(5,2);
INSERT INTO T0611 VALUES(6,9);
INSERT INTO T0611 VALUES(7,1);
INSERT INTO T0611 VALUES(8,-4);
INSERT INTO T0611 VALUES(9,-7);
sql
select
ID,Num,if(Num>lag_1 and Num>lead_1,'是','否') as result
from (
         select id,
                num,
                lag(Num, 1) over (order by id ) as lag_1,
                lead(Num, 1) over (order by ID) as lead_1
         from T0611
     ) t1
order by  id ;

316. 中位数

表中保存了数字的值以及其个数,求取中位数,在此表中,数字为0,0,0,0,0,0,0,1,2,2,2.3,所以中位数为(0+0)/2,这道题目在leedcode上有,记得之前写过一遍

text
0	7
1	1
2	3
3	1
sql
create  table if not exists c0629(
 Number int,Frequency INT
);
insert into  c0629 values (0,7),(1,1),(2,3),(3,1);

请编写一个查询来查找所有数字的中位数并将结果命名为 median 。注意:什么是中位数?当一串数字是奇数个时,例如8,3,5,1,4。我们按顺序排列后为:1,3,4,5,8。那么4就是中位数
当一串数字为偶数个时,例如8,3,5,1,4,2。我们按顺序排列后为:1,2,3,4,5,8。那么(3+4)/2=3.5就是中位数。

sql
select
    avg(n.Number) as median
from
    Numbers as n
where
    n.Frequency >= abs(
        (select sum(Frequency) from Numbers where Number <= n.Number) - 
        (select sum(Frequency) from Numbers where Number >= n.Number)
    )
sql
select avg(number) as median
from
(select Number, frequency,
        sum(frequency) over(order by number asc) as total,
        sum(frequency) over(order by number desc) as total1
from Numbers
order by number asc)as a
where total>=(select sum(frequency) from Numbers)/2
and total1>=(select sum(frequency) from Numbers)/2

可考虑使用其他方法,使用中位数的定义从位置逻辑和值和上来理解

317. 使用sparksql解析json类型的字符串

-- 方法一,使用spark自带的函数get_json_object解析,但是效率比较低

SELECT get_json_object(label_value_text, '$.BUS')
FROM (
SELECT '{"BUS":1,"CAR":1,"DIY":1,"FLT":1,"HTL":1,"PKG":1,"TRN":1,"TTD":1}' AS label_value_text
) t1
LIMIT 10

-- 方法二,from_json的用法

select a.k
from (
select from_json('{"k": "xiecheng", "v": 1.0}','k STRING, v STRING',map("","")) as a
) t1

-- 方法三,json_tuple的使用方法,多项获取,一次解析获取全部的json数据

SELECT json_tuple(label_value_text, 'BUS','CAR')
FROM (
SELECT '{"BUS":1,"CAR":0,"DIY":1,"FLT":1,"HTL":1,"PKG":1,"TRN":1,"TTD":1}' AS label_value_text
) t1

-- 方法四,自主开发的自定义函数,其实很简单,就是使用spark写json处理逻辑,打包上传即可,难点是怎么高效处理(对嵌套的处理,使用的简洁性,但是一般公司都开发了直接用就好了.......)

参考文档:
https://blog.csdn.net/lsr40/article/details/79399166
https://blog.csdn.net/lsr40/article/details/103020021
https://cloud.tencent.com/developer/article/1451308
https://cloud.tencent.com/developer/article/1032532
https://blog.csdn.net/weixin_38750084/article/details/93498986?utm_medium=distribute.pc_relevant.none-task-blog-2~

318. 怪异的排序

text
1	张三	1
1	李四	2
2	张三	1
2	李四	2
3	张三	1
3	李四	2
4	王五	1
4	赵柳	2
5	王五	1
5	赵柳	2
6	王五	1
6	赵柳	2
7	麻七	1
7	赖八	2
8	麻七	1
8	赖八	2
9	麻七	1
9	赖八	2

转变为如下

text
1	张三	1
2	张三	1
3	张三	1
1	李四	2
2	李四	2
3	李四	2
4	王五	1
5	王五	1
6	王五	1
4	赵柳	2
5	赵柳	2
6	赵柳	2
7	麻七	1
8	麻七	1
9	麻七	1
7	赖八	2
8	赖八	2
9	赖八	2
sql
create table weird_order
(
机台号 int,
姓名 char(20),
班组 int
);
INSERT INTO `weird_order` (`机台号`, `姓名`, `班组`)
VALUES
  (1, '张三', 1),
  (1, '李四', 2),
  (2, '张三', 1),
  (2, '李四', 2),
  (3, '张三', 1),
  (3, '李四', 2),
  (4, '王五', 1),
  (4, '赵柳', 2),
  (5, '王五', 1),
  (5, '赵柳', 2),
  (6, '王五', 1),
  (6, '赵柳', 2),
  (7, '麻七', 1),
  (7, '赖八', 2),
  (8, '麻七', 1),
  (8, '赖八', 2),
  (9, '麻七', 1),
  (9, '赖八', 2);

这里的难点就是要对姓名排序,使用row_number来获取编号的最小值,就是姓名的新序号

sql
SELECT
  t.机台号,
  t.姓名,
  t.班组
FROM
  weird_order t
JOIN
    (SELECT 姓名, MIN(原始序号) AS 新序号
    FROM (SELECT *, row_number () over () AS '原始序号'
      FROM
        weird_order) t
    GROUP BY 姓名) tt
    ON tt.姓名 = t.姓名
ORDER BY 新序号,
  班组,
  机台号;

319. 打印成绩单

有两个表:Students 和 Grades,Students 记录了学生的分数,Grades 存储了分数和绩点的对应关系。
Students 包含了三个字段:ID、Name(姓名)、Marks(分数)。
Grades 有三个字段:Grade(绩点)、Min_Mark(最小分值)、Max_Mark(最大分值)
根据这两张表,生成一份学习成绩单,这份成绩单要包含这三个字段:Name、Grade、Mark 。

成绩单需要满足以下几个要求:
绩点低于 8 的学生不显示名字,使用 NULL 代替。
成绩单都得先按照绩点降序排序,对于绩点相同的记录,如果绩点 >= 8,就再按照姓名的字母顺序排序;如果绩点 < 8 ,就再按照分数升序排序。

sql
SELECT
  IF(grade >= 8, name, NULL) AS name,
  grade,
  marks
FROM
  Students
  INNER JOIN Grades
    ON marks BETWEEN min_mark
    AND max_mark
ORDER BY grade DESC,
  IF(grade >= 8, name, marks)

留一个思考题,如果把排序的条件“如果绩点 < 8 ,就再按照分数升序排序”中的“升序排序”改成“降序排序”,你会怎么做?(直接加一个负号?)

320. 完全包含

求左边完全包含右边的

text
SQL数据库开发	数据库
北京	中国
新加坡城	新加坡
sql
CREATE TABLE T0608
(
A VARCHAR(100),
B VARCHAR(100)
);

INSERT INTO T0608 VALUES
('SQL数据库开发','数据库'),
('北京','中国'),
('新加坡城','新加坡');
sql
select  *   from T0608 where  A like  concat('%',B,'%');

练习题 28:每季十题(七-)

坚持了半年,没啥精力找SQL题了,感觉基本上除了递归,函数应用,UDF/UDAF就没啥可写的了,这里就把每月10题改成每季十题吧.......其实也就是凑个数

计划把之前找的SQL题分模块归纳一下,计划第四季度完成

上班有时候看了一下算法大佬写的SQL,其实也就那样,主要就是他们的表多,就是逻辑复杂一点,也没什么复杂SQL处理

321. 用户关系探索

设表名:table0
现有城市网吧访问数据,字段:网吧id,访客id(身份证号),上线时间,下线时间:
规则1: 如果有两个用户在一家网吧的前后上下线时间在10分钟以内,则两人可能认识
规则2: 如果这两个用户在三家以上网吧出现【规则1】的情况,则两人一定认识

该城市上网用户中两人一定认识的组合数。

sql
create table table0(
    wid string,
    uid string,
    ontime string,
    offtime string
)
row format delimited fields terminated by '\t'
sql
insert into table0 values (1,110001,'2020-01-01 12:10:00','2020-01-01 12:30:00');
insert into table0 values (1,110001,'2020-01-01 12:35:00','2020-01-01 12:40:00');
insert into table0 values (1,110002,'2020-01-01 12:50:00','2020-01-01 12:55:00');
insert into table0 values (1,110001,'2020-01-01 13:00:00','2020-01-01 13:10:00');
insert into table0 values (1,110003,'2020-01-01 12:15:00','2020-01-01 13:15:00');

insert into table0 values (2,110001,'2020-01-02 12:10:00','2020-01-02 12:30:00');
insert into table0 values (2,110001,'2020-01-02 12:35:00','2020-01-02 12:40:00');
insert into table0 values (2,110002,'2020-01-02 12:50:00','2020-01-02 12:55:00');
insert into table0 values (2,110003,'2020-01-02 13:00:00','2020-01-02 13:00:00');

insert into table0 values (3,110001,'2020-01-03 12:10:00','2020-01-03 12:30:00');
insert into table0 values (3,110003,'2020-01-03 12:15:00','2020-01-03 12:40:00');
insert into table0 values (3,110001,'2020-01-03 12:50:00','2020-01-03 12:55:00');
insert into table0 values (3,110002,'2020-01-03 13:00:00','2020-01-03 13:10:00');
sql
select count(uid) as com_cnt
from(
    select uid
          ,count(1) as flag
    from(
        select wid
              ,uid
              ,abs(unix_timestamp(ontime,'yyyy-MM-dd HH:mm:ss')-unix_timestamp(lag(ontime,1,'1970-01-01 08:00:00') over(partition by wid order by ontime),'yyyy-MM-dd HH:mm:ss')) / 60 ontime_diff
              ,abs(unix_timestamp(offtime,'yyyy-MM-dd HH:mm:ss')-unix_timestamp(lag(offtime,1,'1970-01-01 08:00:00') over(partition by wid order by offtime),'yyyy-MM-dd HH:mm:ss')) / 60 offtime_diff
        from table0
    ) m
    where ontime_diff<=10 and offtime_diff<=10
    group by uid
) n
where flag>=3

这解法貌似不对把,如果出现在不同网吧的两个人不是同两个人,但是求取的时候就认为他们是同两个人??这里应该要lag用户id进行concat拼接,这里的难点就是排序了,可以去重后group by wid来拼接uid

或者这样,对uid继续排序后拼接

sql
select  concat_ws(',',sort_array(array('1','3','2')))

https://mp.weixin.qq.com/s/U1YiZF8eRlF7yQtCXxEQzw

这个答案是肯定没问题的,就是自连接的SQL性能较差

sql
设表名:table0
字段:wid , uid ,ontime ,offtime
select
    id,
    count(distinct wid) c
from
    (select
        wid,
        concat(t0.uid,t1.uid) as id
    from
        (select
            wid,
            uid,
            unix_timestamp(ontime,'yyyyMMdd HH:mm:ss') as ontime,
            unix_timestamp(offtime,'yyyyMMdd HH:mm:ss') as offtime
        from 
            table0
        )t0
    join
        (select
            wid,
            uid,
            unix_timestamp(ontime,'yyyyMMdd HH:mm:ss') as ontime,
            unix_timestamp(offtime,'yyyyMMdd HH:mm:ss') as offtime
        from 
            table0
        )t1
    on t0.wid=t1.wid
        and t0.uid>t1.uid
        and (abs(t0.ontime-t1.ontime)<10*60 or abs(t0.offtime-t1.offtime)<10*60)
        
    )t0
group by 
    id
having
    c>=3

322. 留存用户

分别统计6.1日活跃玩家
流失率次日回归率 6/2未登陆但是6/3日登陆的玩家 / 6/2未登陆的玩家总数
流失率3日回归率 6/2-6/3未登陆但是6/4日登陆的玩家 / 6/2-6/3未登陆的玩家总数
流失率30日回归率 6/2-6/30未登陆但是7/1日登陆的玩家 / 6/2-6/30未登陆的玩家总数

text
id   login_date
用户id   用户登陆时间
一天同一个用户会登陆多次
sql
-- 由于uid过多,随机选取1000个uid来分析

with x as (
select  distinct  id from app_lo_log where  login_date >= '2021-06-01' and login_date <= '2021-06-02' limit 1000 )

select
       login_date,allover,
sum(allover) over (rows  between  unbounded preceding and 1 preceding)
from (
-- 统计每天的回归玩家
         select count(id) as allover,
                login_date
         from (
-- 取用户在区间最早的登录时间,原因是最早的登录时间不在某个时间区间内,那么这个用户属于login_date的回归玩家
                  select id,
                         date(min(login_date)) as login_date
                  from app_lo_log
                  where login_date >= '2021-06-02'
                    and login_date <= '2021-07-02'
                    and id in (select id from x)
                  group by id
              ) t1
         group by login_date
     ) t2 
order by  login_date

同学提供的写法,但是感觉在求取比率的时候分母不太对,分母求取的应该是在当前之前从未登陆的人,也不太好求取因为存在从未登陆的人(不限制结束时间),另一个问题就是窗口函数改成sum(allover) over (rows between current row and unbounded following )或者sum(allover) over (rows between 1 following and unbounded following )应该更符合业务方提出的需求的含义

323. 偶数对

有一串字符串,有几个类似的,00,11,22,33这样的对子,比如"14,55,00"导出的结果就是2;"14,01,02"导出的结果就是0,使用SQL来解决

思路就是偶数对和11的关系
mysql不支持split函数比较麻烦,这里使用spark

sql
select
id ,sum(if(v1%11 = 0 ,1,0))
from 
(
select 
id,v1 
from 
(
SELECT id,v 
FROM (
    SELECT 1 as id , '19,21,32,22|22,9' as st 
) t
    LATERAL VIEW explode(split(st, '\\|')) tf AS v  
    ) t1 
    LATERAL VIEW explode(split(v, ',')) tf1 AS v1
    ) t2 
    group by id

能不能改进一下解析一步到位?

mysql实现行转列的功能 https://www.cnblogs.com/gered/p/10797012.html

324. 控制窗口大小的使用

有所遗忘,关键平时也没有这种需求的......感觉一天不如一天了.......

PRECEDING:往前
FOLLOWING:往后
CURRENT ROW:当前行
UNBOUNDED:起点,UNBOUNDED PRECEDING 表示从前面的起点, UNBOUNDED FOLLOWING:表示到后面的终点

例如

sql
select name,orderdate,cost,
sum(cost) over() as fullagg, --所有行相加
sum(cost) over(partition by name) as fullaggbyname, --按name分组,组内数据相加
sum(cost) over(partition by name order by orderdate) as fabno, --按name分组,组内数据累加 
sum(cost) over(partition by name order by orderdate rows between unbounded preceding and current row) as mw1   --和fabno一样,由最前面的起点到当前行的聚合 
sum(cost) over(partition by name order by orderdate rows between 1 preceding and current row) as mw2,   --当前行和前面一行做聚合 
sum(cost) over(partition by name order by orderdate rows between 1 preceding and 1 following) as mw3,   --当前行和前边一行及后面一行 
sum(cost) over(partition by name order by orderdate rows between current row and unbounded following) as mw4  --当前行及后面所有行 
over (order by score range between 2 preceding and 2 following) 窗口范围为当前行的数据幅度减2加2后的范围内的数据求和。
from order; 

325. 母店下所有子店

有表dimhtl

text
htlid   type   typeid
子酒店id   如果是0就是母酒店,不是0就是子酒店   母酒店id

现在求取某母酒店下所有的子酒店

sql
select
t1.htlid,t2.htlid
from
dimhtl t1
join  (select * from dimhtl where type <> 0) t2
on t1.type = 0
and t1.typeid = t2.typeid

326. 流失率口径

最近有算有个城市流失率,流失率口径 =这段时间内这些预定人预定了其他城市订单的自然人 /某段时间内取消过去这个城市的订单,但是没有去这个城市的自然人(预订人)

我们不从算法的行程角度来看看问题,就单纯地从数仓的角度回答,对于这个口径的较高执行效率的SQL写法

327.小数点前0丢失的解决方法

小数点前0丢失的解决方法

sql
select
substring(ratio,1,7) || '%'  as ratio
from
(
select case when position('.' in ratio) = 1 then '0'|| ratio else ratio end as ratio
) t1 

328.两种分组top类型需求

  1. 求取客流量在top10城市的,年龄区间占比
text
           上海   北京  广州 ......
60前
60后
70
80
90
....
  1. 求取城市行政区下top10的客源省份的占比
text
               上海   北京  广州 ......
黄浦区
浦东新区
长宁区
...... 

其实这两类需求只是主次不同,第一个需求列为1,第二个需求行为1

329. 同时存在的AID

有表如下

text
AID  BID
1     2
1     5
2     1
2     3
2     5
3     4
3     2
3     5

列AID和BID是一对多的关系,希望将BID中同时存在3和5的AID找出来,预计的结果是AID = 2

很简单,having判断一下数量,注意的细节是同一个AID对于重复的BID的处理

text
having sum(case when  bid = 3 then 1 esle 0 end ) >= 1 and 
sum(case when  bid = 5 then 1 esle 0 end ) >= 1

330. Type类型均分

text
Type Num
A  2
B  3
C  2

希望将每个Type按Num进行均等分,结果如下

text
A 1
A 1
B 1
B 1
B 1
C 1
C 1

方法有很多:比如使用递归来做,构建row_number() 自增键,使用炸裂函数等

方法一:使用hive中的炸裂函数

sql
with x as (
select 'A' as type  ,2 as Num  
union all 
select 'B' , 3 
union all 
select 'C' ,2 
)
select
type,'1' AS m 
from 
x 
LATERAL VIEW POSEXPLODE(SPLIT(SPACE(Num - 1 ),' ')) AS pos,val

SPACE 函数用于生成由N个空格字符的字符串,split按照' ' 进行切分,注意Num数问题

方法二:使用mysql的递归CTE用法,在大数据中递归式一般是不用的,这里复习一下mysql的递归用法

https://www.yiibai.com/mysql/recursive-cte.html

示例:

sql
WITH RECURSIVE cte_count (n)
AS (
      SELECT 1
      UNION ALL
      SELECT n + 1
      FROM cte_count
      WHERE n < 3
    )
SELECT n
FROM cte_count;

参考:

sql
WITH RECURSIVE sql_0904 (Type,Num)
as (
    select  Type,Num from T0904
    union all
    select  Type ,Num -1 from sql_0904 where Num >= 2
    )
select  Type ,1  FROM sql_0904 ORDER BY Type;

补充:
同期在kylin中的写法

text
concat(cast(cast(substring('2021-01-01',1,4) as int ) -1 as varchar),
substring('2021-01-01',5,7))

未来28天在kylin中的写法

text
TIMESTAMPADD(DAY, 28, CURRENT_DATE) 

练习题 29:每季十题(八)

331. 提取JSON中的value值

  1. get_json_object
    语法:get_json_object(json_string, ‘$.key’),注意事项:这个函数每次只能返回一个数据项
sql
select 
get_json_object('{"company":"阿里","age":18}','$.ompany'),
get_json_object('{"company":"拼多多","age":18}','$.age');
  1. json_tuple
    语法:json_tuple(json_string, k1, k2 …),解析多个字段不加 $ hive:函数:json_tuple处理json数据
sql
如下:
hive> select * from json_test;
select * from json_test
OK
1	{"name":"孙先生","carrer":"大数据开发工程师","dream":["开个便利店","去外面逛一逛","看本好书"],"friend":{"friend_1":"MM","friend_2":"NN","friend_3":"BB","friend_4":"VV"}}
2	{"name":"唐女士","carrer":"退休农民","dream":["儿子听话","带孙子"],"friend":{"friend_1":"CC"}}
sql
-- 提取二级格式下的数据(如好友1)
select good_friend_1
from temp_db.json_test
lateral view json_tuple(str,'friend') dd as good_friend
lateral view json_tuple(good_friend,'friend_1') tb as good_friend_1;
查询结果:
MM
CC
 
-- 提取标签中所有的内容(没有的标签,返回null)
select good_friend_1,good_friend_2,good_friend_3
from temp_db.json_test
lateral view json_tuple(str,'friend') dd as good_friend
lateral view json_tuple(good_friend,'friend_1','friend_2','friend_3') tb as good_friend_1,good_friend_2,good_friend_3;
 
查询结果:
MM	NN	BB
CC	NULL	NULL
sql
--dreaming string格式转数组(string不可以直接转数组的,即使string的数据符合数组的格式)
select regexp_replace(regexp_replace(regexp_replace(dreaming, '\\[', ''),'\\]',''),'\\"','')
from temp_db.json_test
lateral view  json_tuple(str,'dream') dd as dreaming;
查询结果:
开个便利店,去外面逛一逛,看本好书
儿子听话,带孙子
  1. 嵌套子查询解析json数组
text
[{“website”:“baidu.com”,“name”:“百度”},{“website”:“google.com”,“name”:“谷歌”}]

解析为

website	name
baidu.com	百度
google.com	谷歌
sql
SELECT explode(split(
    regexp_replace(
        regexp_replace(
            '[
                {"website":"baidu.com","name":"百度"},
                {"website":"google.com","name":"谷歌"}
            ]', 
            '\\[|\\]' , ''), 将json数组两边的中括号去掉
            
              '\\}\\,\\{' , '\\}\\;\\{'), 将json数组元素之间的逗号换成分号
                
                 '\\;') 以分号作为分隔符(split函数以分号作为分隔)
          ); 

嵌套一层json_tuple
select json_tuple(json, 'website', 'name') 
from (
select explode(split(regexp_replace(regexp_replace('[{"website":"baidu.com","name":"百度"},{"website":"google.com","name":"谷歌"}]', '\\[|\\]',''),'\\}\\,\\{','\\}\\;\\{'),'\\;')) 
as json) t;
  1. 使用 lateral view 解析json数组
    lateral view通常和UDTF一起出现,为了解决UDTF不允许在select存在多个字段的问题
text
goods_id	json_str
1,2,3	[{“source”:“7fresh”,“monthSales”:4900,“userCount”:1900,“score”:“9.9”},{“source”:“jd”,“monthSales”:2090,“userCount”:78981,“score”:“9.8”},{“source”:“jdmart”,“monthSales”:6987,“userCount”:1600,“score”:“9.0”}]
sql
select good_id,get_json_object(sale_json,'$.monthSales') as monthSales
from tableName 
LATERAL VIEW explode(split(goods_id,','))goods as good_id 
LATERAL VIEW explode(split(regexp_replace(regexp_replace(json_str , '\\[|\\]',''),'\\}\\,\\{','\\}\\;\\{'),'\\;')) sales as sale_json;

332. 提取JSON中 key值

text
[{“website”:“baidu.com”,“name”:“百度”},{“website”:“google.com”,“name”:“谷歌”}]
sql
select rn
      ,val as key
from(
    select pos+1 as rn
          ,val
    from(
        select regexp_replace(translate('[{"website":"baidu.com","name":"百度"},{"website":"google.com","name":"谷歌"}]'
                          ,'[]{}""','') ,'\,','\:') as str
    ) t1 lateral view posexplode(split(str,':')) t2 as pos,val
) m 
where rn%2=1 

提供了一种方法,主要的思路还是正则和炸裂的使用

text
website:baidu.com:name:百度:website:google.com:name:谷歌

这里有个难点是怎么获取奇数值,作者使用了posexplode函数,第一个值是索引,第二是值是value值,我在想其实不用吧 ,--> :

333. 遍历字符串

  1. 'a,b,c,d,e,f'
sql
select posexplode(split('a,b,c,d,e,f',','))
  1. "abcdef"

先根据字符串长度生成对应的索引

sql
select posexplode(split(space(length("abcdef")-1),' '))

针对生成的索引值按行进行展开

sql
select 'abcdef' as str
      ,pos --索引
      ,substr("abcdef",pos+1,1)
      ,substr("abcdef",0,pos+1)
from(
select posexplode(split(space(length("abcdef")-1),' '))
) t

(1)利用posexplode()函数生成索引
(2)已知某个长度值,根据长度值生成索引的方法。space()函数及posexplode()函数
(3)通过索引值及substr()函数获取当前索引处的字符串值。

334. 删除字符串中多余的字符 translate(input, from, to)

input:输入字符串【集是要被替换的字符串】
from:需要匹配的字符【即需要被替换的字符】,这里一定要注意是字符不是字符串
to :用哪些字符来替换被匹配到的字符

  1. 如果 from 字符串长度=to的字符串长度,如translate(“abcdef-abcdef”,“abcdef”,“123456”);替换不是说把"abcdef"替换成"123456",而是把a替换成1,把b替换成2,把c替换成3,把d替换成4,e替换成5,f替换成6。
  2. 如果 from 字符串长度>to的字符串长度 ,例如TRANSLATE(‘abcdef-abcdef’,‘adbc’,‘123’) 意思是把 a替换为1,b替换为2,c替换为3,d替换为空,即删除掉
  3. 如果 from里有重复字符 比如abca,1231,重复的字符a对应to的替换不会起作用
  4. from长度<to的长度,不报错但是to里面长的字符没有意义。
sql
select 
TRANSLATE('abcdef-abcdef','abcd','1234'),--1234ef-1234ef
TRANSLATE('abcdef-abcdef','abcd','123'), --123ef-123ef
TRANSLATE ('abcdaabbaaabbb','aa','12'),--1bcd11bb111bbb
TRANSLATE ('abcdaabbaaabbb','a','123')--1bcd11bb111bbb

335. 分离字符串中的字符和数字 repeat()

  1. 转换为指定特征字符或特征数字
sql
select data
      ,translate(lower(data),'abcdefghijklmnopqrstuvwxyz',repeat('*',26))
      ,translate(lower(data),'0123456789',repeat('$',10))
from books
  1. 删除指定的特征字符
sql
select data
      ,cast(regexp_replace(translate(lower(data),'abcdefghijklmnopqrstuvwxyz',repeat('*',26)),'\\*','') as bigint) as book_money
      ,regexp_replace(translate(lower(data),'0123456789',repeat('$',10)),'\\$','')  as book_name
from books	

336. 某个字符是否在字符串中

  1. 用like正则匹配
  2. 用locate()函数判断
  3. 用regexp正则匹配。注意此时regxp()里面的正则为regexp(’.* 1.*’)

337. HIVE日期函数大全

sql
【hive 日期函数 大全】Hive常用日期函数整理
 
注意:1)  hive 没有 to_char函数  2) HIVE 日期函数只识别 年-月-日 不能识别 年-月 ,所以处理月份的时候需要特殊处理
 
1)hive 字符创拼接:
CONCAT(string A, string B…)
SELECT CONCAT('2019','05','11');
2) 字符截取
select substr(add_months(from_unixtime((unix_timestamp('2015-09','yyyy-MM')),'yyyy-MM-dd'),-1),0,7);  
SELECT SUBSTR(from_unixtime((unix_timestamp('201509','yyyyMM')),'yyyyMMdd'),0,6);
SELECT SUBSTR(from_unixtime((unix_timestamp('201509','yyyyMM')),'yyyy-MM-dd'),0,7);
 
hive (felix)> SELECT from_unixtime(unix_timestamp(cast('201509' as string),'yyyyMM'),'yyyy-MM-dd') ;
2015-09-01
Time taken: 0.06 seconds, Fetched: 1 row(s)
hive (felix)> SELECT from_unixtime(unix_timestamp(cast('201509' as string),'yyyyMM'),'yyyy-MM') ;
2015-09
 
select from_unixtime(unix_timestamp(add_months(from_unixtime((unix_timestamp('201509','yyyyMM')),'yyyy-MM-dd'),-1),'yyyy-MM-dd'),'YYYYMM') time_list
 
 
3) 时间区间获取
 
4) 中英文日期转换
hive (default)> select from_unixtime((unix_timestamp('201509','yyyyMM')),'MMM-YY');
OK
Sep-15
Time taken: 0.06 seconds, Fetched: 1 row(s)
 
hive (default)> SELECT from_unixtime(unix_timestamp('Sep-19','MMM-YY'),'yyyyMM');
OK
201812
---英文日期大写
hive (default)> select upper(from_unixtime((unix_timestamp('201509','yyyyMM')),'MMM-YY'));
OK
SEP-15
Time taken: 0.062 seconds, Fetched: 1 row(s)
 
 
 
1.unix_timestamp()
返回当前时区的unix时间戳
返回类型:bigint
hive (default)> SELECT UNIX_TIMESTAMP();
 
2.from_unixtime(bigint unixtime[,string format])
时间戳转日期函数
返回类型:string
hive (default)> select from_unixtime(unix_timestamp(),'yyyyMMdd') ;
20160614
 
3.unix_timestamp(string date)
返回指定日期格式的的时间戳
返回类型:bigint
注意:如果后面只有date参数,date的形式必须为'yyyy-MM-dd HH:mm:ss'的形式。
hive (default)> select unix_timestamp('2020-05-01');
NULL
hive (default)> select unix_timestamp('2020-05-01 00:00:00');
1464710400
 
4.unix_timestamp(string date,string pattern)
返回指定日期格式的时间戳
返回类型:bigint
hive (default)> select unix_timestamp('2020-05-01','yyyy-MM-dd');
1449331200
 
5.to_date(string date)
返回时间字段中的日期部分 必须是yyyy-MM-dd格式
返回类型:string
 
说明: 返回日期时间字段中的日期部分。只能识别到 “年-月-日” 级别的时间,无法识别 “年-月” 级别的时间。
--1) 注意 使用年月,to_date 日期是识别不了的
hive (default)> select to_date('2016-09');  --有问题,结果为null
OK
NULL 
Time taken: 0.067 seconds, Fetched: 1 row(s)
 
hive (default)> select add_months('2020-05-01',-1);
OK
2020-04-01
 
hive (default)> select to_date('2020-05-01 00:00:00') ;
2020-05-01
 
hive (default)> select to_date('2020-05-01');
2020-05-01
 
 
6.year(string date)
返回时间字段中的年
返回类型:int
hive (default)> select year('2020-05-01 00:00:00') ;
2016
hive (default)> select year('2020-05-01') ;
2016
 
7.month(string date)
返回时间字段中的月
返回类型:int
hive (default)> select month('2020-05-01') ;
6
hive (default)> select month('2020-05-01');
6
 
8.day(string date)
返回时间字段中的天
返回类型:int
hive (default)> select day('2020-05-01') ;
1
 
9、day:返回日期中的天
 
select day('2015-04-13 11:32:12');
输出:13
 
10、hour:返回日期中的小时
 
select hour('2015-04-13 11:32:12');
输出:11
 
11、minute:返回日期中的分钟
 
select minute('2015-04-13 11:32:12');
输出:32
 
12、second:返回日期中的秒
 
select second('2015-04-13 11:32:56');
输出:56
 
 
13.weekofyear(string date)
返回时间字段是本年的第多少周
返回类型:int
hive (default)> select weekofyear('2020-05-01') ;
22
 
14.datediff(string enddate,string begindate)
返回enddate与begindate之间的时间差的天数
返回类型:int
hive (default)> select datediff('2020-05-01','2016-05-01') ;
31
--DEMO 2 
hive (default)> SELECT datediff('2020-05-01 00:00:00','2016-05-01 23:00:00');
OK
31
 
15.date_add(string date,int days)
返回date增加days天后的日期
返回类型:string
hive (default)> select date_add('2020-05-01',15) ;
2020-05-16
 
16.date_sub(string date,int days)
返回date减少days天后的日期
返回类型:string
hive (default)> select date_sub('2020-05-01',15) ;
2016-05-17
 
17:Hive中取最近30天数据
datediff(CURRENT_TIMESTAMP ,gmt_create)<=30 
 
18、Hive中 两个日期相差多少小时
select (unix_timestamp('2018-05-25 12:03:55') - unix_timestamp('2018-05-25 11:03:55'))/3600
输出:1
19、Hive中 两个日期相差多少分钟
select (unix_timestamp('2018-05-25 12:03:55') - unix_timestamp('2018-05-25 11:03:55'))/60
输出:60
 
20、hive 计算某一个日期属于星期几,如2018-05-20 是星期日
SELECT IF(pmod(datediff('2018-05-20', '1920-01-01') - 3, 7)='0', 7, pmod(datediff('2018-05-20', '1920-01-01') - 3, 7)) 
输出:7
 
 
21、hive返回上个月第一天和最后一天
--上个月第一天
select trunc(add_months('2020-05-08',-1),'MM');  --只能识别 年-月-日 
select trunc(add_months(CURRENT_TIMESTAMP,-1),'MM')
 
hive (default)> select trunc(add_months('2020-05',-1),'MM'); 
OK
NULL
Time taken: 0.067 seconds, Fetched: 1 row(s)
hive (default)> select trunc(add_months('2020-05-08',-1),'MM'); 
OK
2020-04-01
Time taken: 0.079 seconds, Fetched: 1 row(s)
hive (default)> 
 
 
 
select concat(substr(add_months(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),-1),1,7),'-01'); 

338. 时间序列--补全数据

text
date_id   a   b    c
2014     AB  12    bc
2015         23    
2016               d
2017     BC 

如何使用最新数据补全表格

date_id   a   b    c
2014     AB  12    bc
2015     AB  23    bc
2016     AB  23    d
2017     BC  23    d
sql
select 
  date_id, 
  first_value(a) over(partition by aa order by date_id) as a,
  first_value(b) over(partition by bb order by date_id) as b,
  first_value(c) over(partition by cc order by date_id) as c
from
(
  select 
    date_id,
    a,
    b,
    c,
    count(a) over(order by date_id) as aa,
    count(b) over(order by date_id) as bb,
    count(c) over(order by date_id) as cc
  from t20
)tmp1;

339. like,not like,rlike, regexp的区别和使用详解

  1. Rlike功能和like功能大致一样,like是后面只支持简单表达式匹配(_%),而rlike则支持标准正则表达式语法。所以如果正则表达式使用熟练的话,建议使用rlike,功能更加强大。所有的like匹配都可以被替换成rlike。反之,则不行。但是注意:like是从头逐一字符匹配的,是全部匹配,但是rlike则不是,可以从任意部位匹配,而且不是全部匹配。
  2. NOT A LIKE B是LIKE的结果否定,如果like匹配结果时true,则not…like的匹配结果时false,反之也是结果也是相对。实际中也可以使用 A NOT LIKE B,也是LIKE的否定,与 NOT A LIKE B一样。当然前提要排除出现null问题,null值这个奇葩除外,null的结果都是null值。
  3. 同理NOT RLIKE 的使用,也是NOT A RLIKE B是对RLIKE的否定。当然前提要排除出现null问题,null值这个奇葩除外,null的结果都是null值。

340. 统计字符串中字符的个数

  1. 用regexp_replace()函数将要计算的字符替换为’'
  2. 用字符串的总长度减去替换字符后的串长度,得到要计算的字符总长度
sql
select (length("HELLO HELLO")) - (length(regexp_replace("HELLO HELLO","LL",'')))

练习题 30:每季十题(九)

340. 用户连续消费的月份【小红书一面】

text
有表log_consume
uid,order_time,order_price

A,2022-01-01,100
A,2022-01-02,100
A,2022-02-02,100
A,2022-03-02,100
A,2022-04-02,100
A,2022-05-02,100
B,2021-01-02,100
B,2021-01-02,100
B,2021-03-02,100
B,2021-05-02,100
B,2021-07-02,100
B,2021-11-02,100
B,2021-12-02,100
B,2022-01-02,100
B,2022-02-02,100
sql
create table log_consume(
    uid  varchar(10),
    order_time date,
    order_price double
);

insert into log_consume value('A','2022-01-01',100);
insert into log_consume value('A','2022-01-02',100);
insert into log_consume value('A','2022-02-02',100);
insert into log_consume value('A','2022-03-02',100);
insert into log_consume value('A','2022-04-02',100);
insert into log_consume value('A','2022-05-02',100);
insert into log_consume value('B','2021-01-02',100);
insert into log_consume value('B','2021-01-02',100);
insert into log_consume value('B','2021-03-02',100);
insert into log_consume value('B','2021-05-02',100);
insert into log_consume value('B','2021-07-02',100);
insert into log_consume value('B','2021-11-02',100);
insert into log_consume value('B','2021-12-02',100);
insert into log_consume value('B','2022-01-02',100);
insert into log_consume value('B','2022-02-02',100);

也就是连续登陆案例的变形题

  1. 求用户连续消费的月份

我这mysql开窗出bug了,先这样写吧

sql
with x as (
                         select uid,
                                order_month,
                                 IF(month_sum = 1, 0, 1)  as tag
                         from (
                                  SELECT uid,
                                         order_month,
                                         lag_order_month,
                                         ((year(order_month) - year(lag_order_month)) * 12 + month(order_month) -
                                          month(lag_order_month)) as month_sum
                                  FROM (
                                           select uid,
                                                  order_month,
                                                  lag(order_month, 1, order_month)
                                                      over (partition by uid order by order_month asc ) as lag_order_month
                                           from (
                                                    SELECT uid, concat(SUBSTR(order_time, 1, 7), '-01') AS order_month
                                                    FROM log_consume
                                                    GROUP BY uid, concat(SUBSTR(order_time, 1, 7), '-01')
                                                ) t1
                                       ) t2
                              ) t3 )
select
uid,k,group_concat(order_month)
from (
select
uid,
order_month,tag,sum(tag) over (), sum(tag) over (partition by uid),sum(tag) over (partition by uid order by order_month) as k
from x ) t1 group by uid,k having count(1) >= 2;

问题的解决
为什么会出现这种结果,我很诧异.....

sql
select uid, order_month, tag,sum(tag) over (partition by uid order by order_month rows between unbounded preceding and current row)
from (
                         select uid,
                                order_month,
                                 IF(month_sum = 1, 0, 1)  as tag
                         from (
                                  SELECT uid,
                                         order_month,
                                         lag_order_month,
                                         ((year(order_month) - year(lag_order_month)) * 12 + month(order_month) -
                                          month(lag_order_month)) as month_sum
                                  FROM (
                                           select uid,
                                                  order_month,
                                                  lag(order_month, 1, order_month)
                                                      over (partition by uid order by order_month asc ) as lag_order_month
                                           from (
                                                    SELECT uid, concat(SUBSTR(order_time, 1, 7), '-01') AS order_month
                                                    FROM log_consume
                                                    GROUP BY uid, concat(SUBSTR(order_time, 1, 7), '-01')
                                                ) t1
                                       ) t2
                              ) t3 ) t4;

要显式显示窗口的大小规则.......这样就没问题

341. 用户连续消费两个月,但是第三个月不消费【小红书一面】

就是求取连续消费两个月
count(1) = 2 即可

如果跨年重新计算呢?

342. 基于扫码记录查找密接人员

sql
create table log_trail(
    uid varchar(11),
    area varchar(10),
    scan_time varchar(24)

);

insert into log_trail value ('1000001','100A','2022-01-01 09:01:09');
insert into log_trail value ('1000001','100A','2022-01-01 12:01:09');
insert into log_trail value ('1000001','100A','2022-01-01 13:01:09');
insert into log_trail value ('1000001','100B','2022-01-01 14:01:09');
insert into log_trail value ('1000001','100B','2022-01-01 19:01:09');
insert into log_trail value ('1000001','100A','2022-01-01 20:01:09');
insert into log_trail value ('1000001','100A','2022-01-01 21:01:09');
insert into log_trail value ('1000001','100A','2022-01-01 23:01:09');

insert into log_trail value ('1000002','100A','2022-01-01 09:01:09');
insert into log_trail value ('1000002','100A','2022-01-01 10:01:09');
insert into log_trail value ('1000002','100A','2022-01-01 11:01:09');
  1. 找到每个用户在每个区域的开始时间和结束时间(存在跨区的情况)
sql
select
uid,area,tag,min(scan_time) as start_time ,max(scan_time) as end_time
from (
select uid, area, scan_time,row_number() over (partition by uid order by scan_time) - row_number() over (partition by uid,area order by scan_time) as tag
from log_trail ) t1
group by uid,area,tag
;
  1. 假如某个用户核酸检查结果为阳性,找出他的伴随人员?伴随规则:在阳性人员停留半小时以上的区域,用户停留时间在半小时以上,并且停留时间和阳性人员有十分钟以上的交集
    分三种情况的
sql
with x as (
select
uid,area,tag,min(scan_time) as start_time ,max(scan_time) as end_time
from (
select uid, area, scan_time,row_number() over (partition by uid order by scan_time) - row_number() over (partition by uid,area order by scan_time) as tag
from log_trail  ) t1
group by uid,area,tag
having  min(scan_time) + interval 30  minute  <=  max(scan_time) )

select t2.uid,t2.uid, t2.area, t2.start_time, t2.end_time
from (
select uid,area,start_time,end_time
from x where uid = '1000002' ) t1
join (
   select uid,area,start_time,end_time
from x where uid <>  '1000002'
    ) t2
on t1.area = t2.area
and  t1.start_time + interval 10  minute <= t2.end_time
and  t2.start_time + interval 10  minute <= t1.end_time

343. 同比、环比增长率

之前有篇博客有讲SQL怎么写
SQL-分组月度环比同比,思路很简单就是偏移量函数结合排序的应用,注意点就是可能某个月没有数据会导致计算错误,需要使用full join 来避免问题的

344. 计算直播间的人气值

直播开播记录表
直播观看记录表

ACU为平均同时在线人数,计算方式为:观众侧观看时长/某场直播的开播时长,没有人观看的时候显示0

345. 地铁换乘线路查询☆

  1. mysql递归
sql
with  recursive t(n) as (
     select  1 as n  -- 初始化
     union  all
     select  n + 1 from t where n < 10  -- 递归式

    )
select  * from t;
sql
CREATE TABLE bj_subway(
  station_id INT NOT NULL PRIMARY KEY,
  line_name  VARCHAR(20) NOT NULL,
  station_name VARCHAR(50) NOT NULL,
  next_station VARCHAR(50) NOT NULL,
  direction VARCHAR(50) NOT NULL
);

-- 初始化数据,目前只有1号线、2号线和8号线的数据
INSERT INTO bj_subway VALUES (1,'1号线','苹果园','古城','苹果园—四惠东');
INSERT INTO bj_subway VALUES (2,'1号线','古城','八角游乐园','苹果园—四惠东');
INSERT INTO bj_subway VALUES (3,'1号线','八角游乐园','八宝山','苹果园—四惠东');
INSERT INTO bj_subway VALUES (4,'1号线','八宝山','玉泉路','苹果园—四惠东');
INSERT INTO bj_subway VALUES (5,'1号线','玉泉路','五棵松','苹果园—四惠东');
INSERT INTO bj_subway VALUES (6,'1号线','五棵松','万寿路','苹果园—四惠东');
INSERT INTO bj_subway VALUES (7,'1号线','万寿路','公主坟','苹果园—四惠东');
INSERT INTO bj_subway VALUES (8,'1号线','公主坟','军事博物馆','苹果园—四惠东');
INSERT INTO bj_subway VALUES (9,'1号线','军事博物馆','木樨地','苹果园—四惠东');
INSERT INTO bj_subway VALUES (10,'1号线','木樨地','南礼士路','苹果园—四惠东');
INSERT INTO bj_subway VALUES (11,'1号线','南礼士路','复兴门','苹果园—四惠东');
INSERT INTO bj_subway VALUES (12,'1号线','复兴门','西单','苹果园—四惠东');
INSERT INTO bj_subway VALUES (13,'1号线','西单','天安门西','苹果园—四惠东');
INSERT INTO bj_subway VALUES (14,'1号线','天安门西','天安门东','苹果园—四惠东');
INSERT INTO bj_subway VALUES (15,'1号线','天安门东','王府井','苹果园—四惠东');
INSERT INTO bj_subway VALUES (16,'1号线','王府井','东单','苹果园—四惠东');
INSERT INTO bj_subway VALUES (17,'1号线','东单','建国门','苹果园—四惠东');
INSERT INTO bj_subway VALUES (18,'1号线','建国门','永安里','苹果园—四惠东');
INSERT INTO bj_subway VALUES (19,'1号线','永安里','国贸','苹果园—四惠东');
INSERT INTO bj_subway VALUES (20,'1号线','国贸','大望路','苹果园—四惠东');
INSERT INTO bj_subway VALUES (21,'1号线','大望路','四惠','苹果园—四惠东');
INSERT INTO bj_subway VALUES (22,'1号线','四惠','四惠东','苹果园—四惠东');
INSERT INTO bj_subway VALUES (23,'1号线','四惠东','四惠','四惠东—苹果园');
INSERT INTO bj_subway VALUES (24,'1号线','四惠','大望路','四惠东—苹果园');
INSERT INTO bj_subway VALUES (25,'1号线','大望路','国贸','四惠东—苹果园');
INSERT INTO bj_subway VALUES (26,'1号线','国贸','永安里','四惠东—苹果园');
INSERT INTO bj_subway VALUES (27,'1号线','永安里','建国门','四惠东—苹果园');
INSERT INTO bj_subway VALUES (28,'1号线','建国门','东单','四惠东—苹果园');
INSERT INTO bj_subway VALUES (29,'1号线','东单','王府井','四惠东—苹果园');
INSERT INTO bj_subway VALUES (30,'1号线','王府井','天安门东','四惠东—苹果园');
INSERT INTO bj_subway VALUES (31,'1号线','天安门东','天安门西','四惠东—苹果园');
INSERT INTO bj_subway VALUES (32,'1号线','天安门西','西单','四惠东—苹果园');
INSERT INTO bj_subway VALUES (33,'1号线','西单','复兴门','四惠东—苹果园');
INSERT INTO bj_subway VALUES (34,'1号线','复兴门','南礼士路','四惠东—苹果园');
INSERT INTO bj_subway VALUES (35,'1号线','南礼士路','木樨地','四惠东—苹果园');
INSERT INTO bj_subway VALUES (36,'1号线','木樨地','军事博物馆','四惠东—苹果园');
INSERT INTO bj_subway VALUES (37,'1号线','军事博物馆','公主坟','四惠东—苹果园');
INSERT INTO bj_subway VALUES (38,'1号线','公主坟','万寿路','四惠东—苹果园');
INSERT INTO bj_subway VALUES (39,'1号线','万寿路','五棵松','四惠东—苹果园');
INSERT INTO bj_subway VALUES (40,'1号线','五棵松','玉泉路','四惠东—苹果园');
INSERT INTO bj_subway VALUES (41,'1号线','玉泉路','八宝山','四惠东—苹果园');
INSERT INTO bj_subway VALUES (42,'1号线','八宝山','八角游乐园','四惠东—苹果园');
INSERT INTO bj_subway VALUES (43,'1号线','八角游乐园','古城','四惠东—苹果园');
INSERT INTO bj_subway VALUES (44,'1号线','古城','苹果园','四惠东—苹果园');
INSERT INTO bj_subway VALUES (45,'2号线','西直门','积水潭','外环');
INSERT INTO bj_subway VALUES (46,'2号线','积水潭','鼓楼大街','外环');
INSERT INTO bj_subway VALUES (47,'2号线','鼓楼大街','安定门','外环');
INSERT INTO bj_subway VALUES (48,'2号线','安定门','雍和宫','外环');
INSERT INTO bj_subway VALUES (49,'2号线','雍和宫','东直门','外环');
INSERT INTO bj_subway VALUES (50,'2号线','东直门','东四十条','外环');
INSERT INTO bj_subway VALUES (51,'2号线','东四十条','朝阳门','外环');
INSERT INTO bj_subway VALUES (52,'2号线','朝阳门','建国门','外环');
INSERT INTO bj_subway VALUES (53,'2号线','建国门','北京站','外环');
INSERT INTO bj_subway VALUES (54,'2号线','北京站','崇文门','外环');
INSERT INTO bj_subway VALUES (55,'2号线','崇文门','前门','外环');
INSERT INTO bj_subway VALUES (56,'2号线','前门','和平门','外环');
INSERT INTO bj_subway VALUES (57,'2号线','和平门','宣武门','外环');
INSERT INTO bj_subway VALUES (58,'2号线','宣武门','长椿街','外环');
INSERT INTO bj_subway VALUES (59,'2号线','长椿街','复兴门','外环');
INSERT INTO bj_subway VALUES (60,'2号线','复兴门','阜成门','外环');
INSERT INTO bj_subway VALUES (61,'2号线','阜成门','车公庄','外环');
INSERT INTO bj_subway VALUES (62,'2号线','车公庄','西直门','外环');
INSERT INTO bj_subway VALUES (63,'2号线','车公庄','阜成门','内环');
INSERT INTO bj_subway VALUES (64,'2号线','阜成门','复兴门','内环');
INSERT INTO bj_subway VALUES (65,'2号线','复兴门','长椿街','内环');
INSERT INTO bj_subway VALUES (66,'2号线','长椿街','宣武门','内环');
INSERT INTO bj_subway VALUES (67,'2号线','宣武门','和平门','内环');
INSERT INTO bj_subway VALUES (68,'2号线','和平门','前门','内环');
INSERT INTO bj_subway VALUES (69,'2号线','前门','崇文门','内环');
INSERT INTO bj_subway VALUES (70,'2号线','崇文门','北京站','内环');
INSERT INTO bj_subway VALUES (71,'2号线','北京站','建国门','内环');
INSERT INTO bj_subway VALUES (72,'2号线','建国门','朝阳门','内环');
INSERT INTO bj_subway VALUES (73,'2号线','朝阳门','东四十条','内环');
INSERT INTO bj_subway VALUES (74,'2号线','东四十条','东直门','内环');
INSERT INTO bj_subway VALUES (75,'2号线','东直门','雍和宫','内环');
INSERT INTO bj_subway VALUES (76,'2号线','雍和宫','安定门','内环');
INSERT INTO bj_subway VALUES (77,'2号线','安定门','鼓楼大街','内环');
INSERT INTO bj_subway VALUES (78,'2号线','鼓楼大街','积水潭','内环');
INSERT INTO bj_subway VALUES (79,'2号线','积水潭','西直门','内环');
INSERT INTO bj_subway VALUES (80,'2号线','西直门','车公庄','外环');
INSERT INTO bj_subway VALUES (81, '8号线', '朱辛庄', '育知路', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (82, '8号线', '育知路', '平西府', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (83, '8号线', '平西府', '回龙观东大街', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (84, '8号线', '回龙观东大街', '霍营', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (85, '8号线', '霍营', '育新', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (86, '8号线', '育新', '西小口', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (87, '8号线', '西小口', '永泰庄', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (88, '8号线', '永泰庄', '林萃桥', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (89, '8号线', '林萃桥', '森林公园南门', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (90, '8号线', '森林公园南门', '奥林匹克公园', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (91, '8号线', '奥林匹克公园', '奥体中心', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (92, '8号线', '奥体中心', '北土城', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (93, '8号线', '北土城', '安华桥', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (94, '8号线', '安华桥', '安德里北街', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (95, '8号线', '安德里北街', '鼓楼大街', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (96, '8号线', '鼓楼大街', '什刹海', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (97, '8号线', '什刹海', '南锣鼓巷', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (98, '8号线', '南锣鼓巷', '中国美术馆', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (99, '8号线', '中国美术馆', '金鱼胡同', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (100, '8号线', '金鱼胡同', '王府井', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (101, '8号线', '王府井', '前门', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (102, '8号线', '前门', '珠市口', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (103, '8号线', '珠市口', '天桥', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (104, '8号线', '天桥', '永定门外', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (105, '8号线', '永定门外', '木樨园', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (106, '8号线', '木樨园', '海户屯', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (107, '8号线', '海户屯', '大红门', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (108, '8号线', '大红门', '大红门南', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (109, '8号线', '大红门南', '和义', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (110, '8号线', '和义', '东高地', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (111, '8号线', '东高地', '火箭万源', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (112, '8号线', '火箭万源', '五福堂', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (113, '8号线', '五福堂', '德茂', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (114, '8号线', '德茂', '瀛海', '朱辛庄-瀛海');
INSERT INTO bj_subway VALUES (115, '8号线', '瀛海', '德茂', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (116, '8号线', '德茂', '五福堂', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (117, '8号线', '五福堂', '火箭万源', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (118, '8号线', '火箭万源', '东高地', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (119, '8号线', '东高地', '和义', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (120, '8号线', '和义', '大红门南', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (121, '8号线', '大红门南', '大红门', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (122, '8号线', '大红门', '海户屯', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (123, '8号线', '海户屯', '木樨园', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (124, '8号线', '木樨园', '永定门外', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (125, '8号线', '永定门外', '天桥', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (126, '8号线', '天桥', '珠市口', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (127, '8号线', '珠市口', '前门', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (128, '8号线', '前门', '王府井', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (129, '8号线', '王府井', '金鱼胡同', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (130, '8号线', '金鱼胡同', '中国美术馆', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (131, '8号线', '中国美术馆', '南锣鼓巷', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (132, '8号线', '南锣鼓巷', '什刹海', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (133, '8号线', '什刹海', '鼓楼大街', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (134, '8号线', '鼓楼大街', '安德里北街', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (135, '8号线', '安德里北街', '安华桥', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (136, '8号线', '安华桥', '北土城', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (137, '8号线', '北土城', '奥体中心', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (138, '8号线', '奥体中心', '奥林匹克公园', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (139, '8号线', '奥林匹克公园', '森林公园南门', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (140, '8号线', '森林公园南门', '林萃桥', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (141, '8号线', '林萃桥', '永泰庄', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (142, '8号线', '永泰庄', '西小口', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (143, '8号线', '西小口', '育新', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (144, '8号线', '育新', '霍营', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (145, '8号线', '霍营', '回龙观东大街', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (146, '8号线', '回龙观东大街', '平西府', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (147, '8号线', '平西府', '育知路', '瀛海-朱辛庄');
INSERT INTO bj_subway VALUES (148, '8号线', '育知路', '朱辛庄', '瀛海-朱辛庄');
sql
WITH RECURSIVE transfer (start_station, stop_station, stops, path) AS (
  SELECT station_name, next_station, 1, CAST(CONCAT(line_name,station_name , '->', line_name,next_station) AS CHAR(1000))
    FROM bj_subway WHERE station_name = '王府井'
   UNION ALL
  SELECT p.start_station, e.next_station, stops + 1, CONCAT(p.path, '->', e.line_name, e.next_station)
    FROM transfer p
    JOIN bj_subway e
      ON p.stop_station = e.station_name AND (INSTR(p.path, e.next_station) = 0)
)
SELECT * FROM transfer WHERE stop_station ='积水潭';

346. 银行可疑支付交易监控

  1. 找出 5 天之内累积转账超过 100 万的账号(限制窗口大小)
  2. 找出相同收付款人5天内连续转账3次以上的记录(限制窗口大小)

347. 微信好友关系

348. 查找优秀员工

集合的交并运算

349. 生成日历表

sql
-- 创建日历表
CREATE TABLE calendar(
  calendar_id    INT NOT NULL PRIMARY KEY, -- 日历编号
  calendar_date  DATE NOT NULL, -- 日历日期
  calendar_year  INT NOT NULL, -- 日历年
  calendar_month INT NOT NULL, -- 日历月
  calendar_day   INT NOT NULL, -- 日历日
  day_of_year    INT NOT NULL, -- 当年中的第几天
  day_of_month   INT NOT NULL, -- 当月中的第几天
  day_of_week    INT NOT NULL, -- 一周中的第几天(星期天为1)
  is_work_day    VARCHAR(1) DEFAULT 'Y' NOT NULL , -- 是否工作日
  CONSTRAINT uk_calendar UNIQUE (calendar_date)
);

--生成2022-01-01开始的一年数据
INSERT INTO calendar
WITH RECURSIVE c(n, dt, y, m, d, doy, dom, dow, work_day) AS (
SELECT 1, '2022-01-01', year('2022-01-01'), month('2022-01-01'), day('2022-01-01'),
       dayofyear('2022-01-01'), dayofmonth('2022-01-01'), dayofweek('2022-01-01'),
       CASE WHEN dayofweek('2022-01-01') IN (2,3,4,5,6) THEN 'Y' ELSE 'N' END work_day
UNION ALL
SELECT n+1,dt + INTERVAL '1' DAY,year(dt + INTERVAL '1' DAY), month(dt + INTERVAL '1' DAY), day(dt + INTERVAL '1' DAY),
       dayofyear(dt + INTERVAL '1' DAY), dayofmonth(dt + INTERVAL '1' DAY), dayofweek(dt + INTERVAL '1' DAY),
       CASE WHEN dayofweek(dt + INTERVAL '1' DAY) IN (2,3,4,5,6) THEN 'Y' ELSE 'N' END work_day
FROM c
WHERE n<365
)
SELECT *
FROM c;

练习题 31:每季十题(十)

350. 连续登陆7天,连续登陆30天的用户

351. 连续点击三次的用户数,中间不能有别人的点击

352. 计算除去部门最高工资和最低工资的平均工资

353. 留存

354. AB球队得分流水表,得到连续三次得分的队员名字和每次赶超对手的球员名字

355. 拉链表

356.

报表同比与环比实现

需求和背景:不能直接对外展示具体的值,让客户自己查询同比,所以需要我们直接给同比值

表头:出行时间(天),到达国家,到达省份,到达城市,景区

解决:
我们的报表系统无法直接求取同比值,想到使用自定义SQL,但是要支持选择时间,我要暴露这个字段,无法实现,只能做表了

其实很简单,我需要在select同时暴露当期值和同期值即可,我的做法是采用两段子句join ,在join的条件上限制

text
concat(CAST(CAST(substring(a.d, 1, 4) AS int) - 1 AS string), substring(a.d, 5, 7)) = b.d

但是这样写,查询的结果与使用底表查结果数据不一致,后来发现使用了错误的join,如果左边的数据为空,就不会有右边的数据了,这样查询结果就不一致了,所有应该使用 full join ,但是又有问题,我们查询的时候会限制数据不为null,所以在select 上需要作出一层判断:如果a的国家/省份/城市/景点为空,则为b

大致如下:

sql
SELECT if(a.d IS NULL, concat(CAST(CAST(substring(b.d, 1, 4) AS int) + 1 AS string), substring(b.d, 5, 7)), a.d)
    , '中国' AS country
    , if(a.prov IS NULL, b.prov , a.prov )
    , if(a.city IS NULL, b.city , a.city )
    , if(a.name IS NULL, b.name , a.name )
    , a.persons AS current_persons, b.persons AS pre_persons, a.order_prices AS current_prices, b.order_prices AS pre_prices
FROM (
    SELECT d, prov , city ,  name 
        , SUM(person_num) AS persons, SUM(order_price) AS order_prices
    FROM tabel
    WHERE d >= '2019-01-01'
        AND country= '中国'
        AND prov IS NOT NULL
        AND city IS NOT NULL
        AND name IS NOT NULL
    GROUP BY d, prov , city ,name 
) a
    full JOIN (
        SELECT d, prov , city , name
            , SUM(person_num) AS persons, SUM(order_price) AS order_prices
        FROM tabel
        WHERE d >= '2019-01-01'
            AND country= '中国'
            AND prov IS NOT NULL
            AND city IS NOT NULL
            AND name IS NOT NULL
        GROUP BY d, prov , city , name 
    ) b
    ON a.prov = b.prov 
        AND a.city = b.city 
        AND a.name = b.name 
        AND concat(CAST(CAST(substring(a.d, 1, 4) AS int) - 1 AS string), substring(a.d, 5, 7)) = b.d

环比同理在join上改变条件即可

分组月度环比与同比

有一个需求是按月份统计环比和同比值,每次都取一遍非常麻烦,同时也容易出错,这里我把要取的数据报表化,这里提供一个模板,这个SQL写了我好久,经过对比数据发现,这样写是没什么问题的,这里提供一些注意事项

  1. 同比环比的定义
    月份同比计算 (2021-01 - 2020-01) / 2020-01
    月份环比计算 (2021-02 - 2021-01) / 2021-01

  2. 在计算同比的时候要注意order by要对月份和年份都要排序,原因是lead 中的order by只指定了一个排序规则,这里都要指定,否则会乱序,这个检查了我好久的时间

  3. 同比和环比的SQL思路
    同比,lead按照业务线分组,之后lead上推度量值,注意要排序使得相同月份,不同年份的数据在一起
    环比,这里也是使用lead来上推,这个没什么注意事项

开始的写法,我这里把同比和环比放在一行了,这种写法的缺点就是不够直观

sql
select 
lag,j_month,basis,relative
FROM
(
SELECT lag, j_month, order_price
    , (order_price - lead_price_basis) * 1.0 / lead_price_basis AS basis
    , relative,
FROM (
    SELECT lag, j_month, order_price, relative
        , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY substring(j_month, 6, 7) DESC,substring(j_month, 0, 4) desc) AS lead_price_basis
    FROM (
        SELECT lag, j_month, order_price
            , (order_price - lead_price_relative) * 1.0 / lead_price_relative AS relative
        FROM (
            SELECT lag, j_month, order_price
                , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY j_month DESC) AS lead_price_relative
            FROM (
                SELECT concat(lag_country, bu) AS lag, j_month, order_price
                FROM (
                    SELECT bu
                        , CASE 
                            WHEN to_country_id = 1 THEN '国内'
                            WHEN to_country_id <> 1 THEN '国外'
                        END AS lag_country, substring(d, 0, 7) AS j_month
                        , round(SUM(order_price), 0) AS order_price
                    FROM table
                    WHERE d >= '2019-01-01'
                        AND bu IN ('机票', '酒店', '度假')
                        AND d <> '4000-01-01'
                    GROUP BY bu, substring(d, 0, 7), CASE 
                            WHEN to_country_id = 1 THEN '国内'
                            WHEN to_country_id <> 1 THEN '国外'
                        END
                ) a
                ORDER BY lag, j_month DESC
            ) b
            WHERE lag IS NOT NULL
        ) c
    ) d
) e
) f 
where  substring(j_month,0,4) = '2021'

后来使用union all 把同比和环比分开显示,然后使用行转列,就得到了下面的效果图,个人认为是一种非常好的报表展示
展示效果

sql
select
lag,j_lag,
MAX(case when substring(j_month,6,7) = '01' then relative  end ) as m1,
MAX(case when substring(j_month,6,7) = '02' then relative  end ) as m2,
MAX(case when substring(j_month,6,7) = '03' then relative  end ) as m3,
MAX(case when substring(j_month,6,7) = '04' then relative  end ) as m4,
MAX(case when substring(j_month,6,7) = '05' then relative  end ) as m5,
MAX(case when substring(j_month,6,7) = '06' then relative  end ) as m6,
MAX(case when substring(j_month,6,7) = '07' then relative  end ) as m7,
MAX(case when substring(j_month,6,7) = '08' then relative  end ) as m8,
MAX(case when substring(j_month,6,7) = '09' then relative  end ) as m9,
MAX(case when substring(j_month,6,7) = '10' then relative  end ) as m10,
MAX(case when substring(j_month,6,7) = '11' then relative  end ) as m11,
MAX(case when substring(j_month,6,7) = '12' then relative  end ) as m12
from 
(
SELECT lag, '环比' AS j_lag, j_month
    , (order_price - lead_price_relative) * 1.0 / lead_price_relative AS relative
FROM (
    SELECT lag, j_month, order_price
        , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY j_month DESC) AS lead_price_relative
    FROM (
        SELECT concat(lag_country, bu) AS lag, j_month, order_price
        FROM (
            SELECT bu
                , CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END AS lag_country, substring(d, 0, 7) AS j_month
                , round(SUM(order_price), 0) AS order_price
            FROM table
            WHERE d >= '2019-01-01'
                AND bu IN ('机票', '酒店', '度假')
                AND d <> '4000-01-01'
            GROUP BY bu, substring(d, 0, 7), CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END
        ) a
    ) b
    WHERE lag IS NOT NULL
) c
UNION ALL
(
SELECT lag, '同比' , j_month
    , (order_price - lead_price_basis) * 1.0 / lead_price_basis 
FROM (
    SELECT lag, j_month, order_price
        , lead(order_price, 1, NULL) OVER (PARTITION BY lag ORDER BY substring(j_month, 6, 7) DESC,substring(j_month, 0, 4) desc) AS lead_price_basis
    FROM (
        SELECT concat(lag_country, bu) AS lag, j_month, order_price
        FROM (
            SELECT bu
                , CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END AS lag_country, substring(d, 0, 7) AS j_month
                , round(SUM(order_price), 0) AS order_price
            FROM table
            WHERE d >= '2019-01-01'
                AND bu IN ('机票', '酒店', '度假')
                AND d <> '4000-01-01'
            GROUP BY bu, substring(d, 0, 7), CASE 
                    WHEN to_country_id = 1 THEN '国内'
                    WHEN to_country_id <> 1 THEN '国外'
                END
        ) a
    ) b
    WHERE lag IS NOT NULL
) c
)
) 
WHERE substring(j_month, 0, 4) = '2021'
GROUP by lag,j_lag
order by substring(lag,3,4),substring(lag,0,2),j_lag

同时我们要对多月份进行汇总计算同比值,如果在这些报表上直接添加汇总是非常麻烦的,需求也是易变的,这里要对每一年的sum(度量)进行报表化,分业务类型,这个报表是简单的,直接分别统计不同年份,直接 union all ,然后使用行转列转变格式即可,还是非常简单的,我们基于这张表来计算多月份的同比就比较简单了,就不用每次麻烦取数了,这张报表展示如下
报表的展示

完成这个需求,我发现SQL的设计同SQL的优化一样重要,如果这个SQL得出的结果不够直观还要二次处理非常低效

数仓面试题(快手 2020)

摘取一些SQL题

1.用户登陆日志

app, user_id, datetime
a1,user1,2020-01-01 00:00:00
a2,user2,2020-01-01 00:00:01
a3,user3,2020-01-01 00:00:02
a4,user4,2020-01-01 00:00:03
……
输出每个app下访问次数最多的5个用户

sql
with x as (
select
app,user_id,count(1) as rn
from
table1 
group by app,user_id
)
select 
t.app,
t.user_id
from 
(
select
app,
user_id,
row_number() over(partition by app order by rn desc) as max_user
from 
x
) as t 
where t.max_user <= 5

2.认识的组合数

现有城市网吧访问数据,字段:网吧id,访客id(身份证号),上线时间,下线时间
规则1、如果有两个用户在一家网吧的前后上下线时间在10分钟以内,则两人可能认识
规则2、如果这两个用户在三家以上网吧出现【规则1】的情况,则两人一定认识
需求:
该城市上网用户中两人一定认识的组合数

sql
//自连接
//最初是限制了t0.uid!=t1.uid,这是筛选出同一个网吧不同id的组合,但是这样会有个问题,A-B与B-A实际上是一个意思,却出现了两条。我们只需要一条数据就可以了,能说明A与B是认识的。在这里是取B-A。或者t0.uid<t1.uid也可以的
sql
设表名:table0
字段:wid , uid ,ontime ,offtime
select
	id,
	count(distinct wid) c
from
	(select
		wid,
		concat(t0.uid,t1.uid) as id
	from
		(select
			wid,
			uid,
			unix_timestamp(ontime,'yyyyMMdd HH:mm:ss') as ontime,
			unix_timestamp(offtime,'yyyyMMdd HH:mm:ss') as offtime
		from 
			table0
		)t0
	join
		(select
			wid,
			uid,
			unix_timestamp(ontime,'yyyyMMdd HH:mm:ss') as ontime,
			unix_timestamp(offtime,'yyyyMMdd HH:mm:ss') as offtime
		from 
			table0
		)t1
	on t0.wid=t1.wid
	    and t0.uid>t1.uid
		and (abs(t0.ontime-t1.ontime)<10*60 or abs(t0.offtime-t1.offtime)<10*60)
		
	)t0
group by 
	id
having
	c>=3

方法二,来自王知无大数据(保留答案,这里有个问题就是出现在不同网吧的可能不是同两个人,这里应该要lag用户id进行concat拼接,这里的难点就是排序了,可以在窗口中预先按照uid来排序来避免这个问题)

sql
select count(uid) as com_cnt
from(
    select uid
          ,count(1) as flag
    from(
        select wid
              ,uid
              ,abs(unix_timestamp(ontime,'yyyy-MM-dd HH:mm:ss')-unix_timestamp(lag(ontime,1,'1970-01-01 08:00:00') over(partition by wid order by ontime),'yyyy-MM-dd HH:mm:ss')) / 60 ontime_diff
              ,abs(unix_timestamp(offtime,'yyyy-MM-dd HH:mm:ss')-unix_timestamp(lag(offtime,1,'1970-01-01 08:00:00') over(partition by wid order by offtime),'yyyy-MM-dd HH:mm:ss')) / 60 offtime_diff
        from table0
    ) m
    where ontime_diff<=10 and offtime_diff<=10
    group by uid
) n
where flag>=3

3.收入前一万

现在有中国人从1980年到2020年每年每人的收入记录表A如下:
id,year,income
求每年收入前一万的人

sql
with x as (
select
id,year,income,
row_number() over(partition by year ,substr(income,1,4) order by income desc ) as rn  
from 
table3
where rn <= 10000
) 
select 
t.id,
t.year
from 
(
select
id,year,income,
row_number() over(partition by year order by income desc ) as rm 
from 
x 
where rm <= 10000
) t
text
spark中action算子top获取前1万,思想是分治,每个组获取前一万,然后在reduce端汇总
↑↓ 选择↵ 打开esc 关闭