SQL是关于集合的

时间:2023-03-09 03:33:46
SQL是关于集合的

一 以面向集合的思维方式来思考

公司里每个工作岗位上干了同样年数的员工列表

select  emplyee_id  from  job_history  group by  employee_id

having  min(round(months_between(start_date,end_date)/12,0))  =  max(round(months_between(start_date,end_date)/12,0));

一个顾客在订单之间的平均天数

select  (max(trunc(order_date))  -  min(trunc(order_date)))  /  count(*)  avg_days_between  from  orders  where customer_id  =  102;

二 集合运算

与联结的区别就在于联结是用来将不同表中的列组合起来形成一行。集合运算比较所输入查询的所有行并返回一个不包含重复值的行集。

union all: 返回两个集合中的所有行,包含重复。

union:     返回来自所有输入查询的不包含重复值的结果集。

minus:    返回在数据行源A中存在但是在B中不存在的数据行集

intersect:返回A和B中都存在的数据行集。

三 集合与空值

空值与非直观结果

除非显示声明,它们不会被包含在结果集中。

select  *  from  emp  where  doptno  not  in  (10,20,30)  or  deptno  is  null;

空值与group  by和order  by

默认的排序规则就是将空值放在最后。如果你想把空值放在最前面,只需要在order  by字句后面加上nulls  first

select  comm,count(*)  ctr  from  emp  group  by  comm  order  by  comm  nulls  first;