1,使用group by 子句
group by 子句将表分为几组,此子句通常与为每个这样的组生产总结值的聚集函数组合。
使用不带聚集的group by 子句与在select 子句中使用的distinct(或unique)关键字很相似。
select distinct customer_num from orders;
selecct customer_num from orders group by customer_num;
group by 子句将行收集到组中,因此每一组中的每一行具有相同的客户号。在没有选择任何其它列的情况下,结果是唯一的customer_num值的列表。select order_num,count(*) number,sum(total_price) price from items group by 1 order by 3;select o.order_num,sum(i.total_price) from order o,items i where o.order_date > '01/01/98'
and ocustomer_num = 110 and o.order_num = i.order_num group by o.order_num;使用having子句
要完成group by 子句,使用having 子句来在构成组之后将一个或多个限制条件应用于这些组。having子句对组的影响类似于
where 子句限制个别行的方式,使用having子句的一个优点是可以在搜索条件中包括聚集,而在where子句的搜索条件中却不能包括聚集。每个having条件将组的一列或一个聚集表达式与组的另一个聚集表达式或与常量作比较。可以使用having来对列值或组列表中的聚集值设置条件。下面的语句返回具有两个商品以上的订单上每个商品的平均总价格。having子句在每个构成的测试组,并选择由两行以上构成的那些组。
select order_num,count(*) number,avg(total_price) average from items group by order_num having count(*) > 2;如果不带group by 子句使用having子句,则该having条件适应雨满足搜索条件的所有行。换言之,满足搜索条件的所有行构成一个组。
select avg(total_price) average from items having count(*) > 2;select o.order_num,sum(i.total_price) price, paid_date - order_date span from orders o,items i
where o.order_date > '01/01/98'
and o.customer_num > 110
and o.order_num = i.order_num
group by 1,3
having count(*) < 5
order by 3
into temp temptab1;创建高级连接自连接
连接不一定都是涉及两个不同的表。可以将表连接至它本身,缠结自连接。当想要将列中的值与同一列中的其它值进行比较时,将表连接
至它自身非常有用。要创建自连接,在from 子句中列示表两次,并且每次为它指定不同的别名。与表之间的连接一样,可以在自连接中使用算术表达式。
可以测试空值,可以使用order by 子句来以升序或将序对指定列中的值进行排序。select x.order_num,x.ship_weight,x,ship_date,y.order_num,y.ship_weight,y.ship_date from order x,order y
where x.ship_weight >= 5*y.ship_date
and x.ship_date is not null
and y.ship_date is not null
order by x.ship_date;如果想要将自连接的结果存储到临时表中,则将Into temp子句追加到select语句中,并至少对一组列指定显示标号,以重命名这些列。否则,
重复列名将导致错误,并且不会创建临时表。select x.order_num orders1,x.po_num purch1,
x.ship_date ship1,y.order_num orders2,
y.po_num purch2,y.ship_date ship2
from order x,orders y 
where x.ship_weight >= 5*y.ship_weight
and x.ship_date is not null
and y.ship_date is not null
order by orders1,orders2
into temp shipping;自连接子句三次
select s1.manu_code,s2.manu_code,s3.manu_code,
s1.stock_num,s1.descripton
from stock s1,stock s2,stock s3
where s1.stock_num = s2.stock_num
and s2.stock_num = s3.stock_num
and s1.manu_code < s2.manu_code
and s2.manu_code < s3.manu_code 
order by stock_num;如果想要从payroll表选择行来确定那些职员的薪水高于他们的经理,按照下面select 语句所示来构造自连接:
select emp.employee_num,emp.gross_pay,emp.level,
emp.detp_num,mgr.employee_num,mgr.gross_pay,
mgr.dept_num,mgr.level
from payroll emp,payroll mgr
where emp.gross_pay > mgr.gross_pay
and emp.level < mgr.level
and emp.dept_num = mgr.dept_num
order by 4;