SQL之五
1. 分组和排序
Order by:对产生的输出排序,任意列都可以使用(甚至非选择的列也可以使用)不一定需要。
Group by:对行分组,但输出可能不是分组的顺序,只可能选择列或表达式列,而且必须使用每个选择列表达式如果与聚集函数一起使用列(或表达式),则必须使用。
举例说明:
Select order_num,count() as items from OrderItems group by order_num having count() >= 3 order by items,order_num;
订购数目大于3的订单分组按数目排序
2. select子句顺序
3.使用子查询进行过滤
逐渐的深入举例说明:
(1) prod_id为RGAN01的所有订单物品,检索其order_num列
select order_num from OrderItems where prod_id=’RGAN01’;
(2) 查询与订单20007和20008相关的顾客ID
Select cust_id from Orders where order_num in (20007,20008);
(3) 结合上面的两个查询把第一个查询变为子查询
Select cust_id from Orders where order_num in (select order_num from OrderItems where prod_id=’RGAN01’);
分析:在select语句中子查询总是从内向外处理,先执行的语句:
Select order_num from OrderItems where prod_id = ‘RGAN01’;
假如这时候查询出来的值只有20007,20008这个时候执行的语句:
Select cust_id from Orders where order_num in (20007,20008);
举例2:上面(3)将RGAN01的所有顾客的id查询出来了,现在要检索这些顾客ID的顾客信息。
Select cust_name,cust_name_contact from Customers
where cust_id
in (select cust_id from Orders where order_num in(select order_num from OrderItems where prod_id = ‘RGAN01’));
分析:这样初看可能不好理解,但是OrderItems,Orders,Customers这三个表存在一定的联系,执行都是从里到外。
注意:子查询的select语句只能查询单个列。如果在子查询中检索多个列将返回错误。
3. 使用计算字段子查询
逐渐深入举例说明:
下面的代码对顾客1000000001的订单进行计数
Select count(*) as orders from Orders where cust_id=’1000000001’;
要对每个顾客执行count(*),应该将它作为一个子查询
Select cust_name,cust_state,(select count(*) from Orders where Orders.cust_id = Customers.cust_id) as orders from Customers order by cust_name;
分析:这里返回的是三列:cust_name,cust_state,orders。Orders是一个计算字段,它是由圆括号中的子查询建立的。
在深入的列子:
如果对上面的count(*)的数要不为0
这时候的写法注意了
Select a.cust_name,a.orders
from (Select cust_name,cust_state,(select count(*) from Orders where Orders.cust_id = Customers.cust_id) as orders from Customers order by cust_name) a where a.orders <> 0;