創(chuàng)建分組
select vend_id, count(*) as num_prods
from products
group by vend_id;
group by 語(yǔ)句的規(guī)定:
- 可以包含任意數(shù)目的列,因而可以對(duì)分組進(jìn)行嵌套
- 必須出現(xiàn)在where語(yǔ)句之后,having語(yǔ)句之前
等等
過(guò)濾分組
過(guò)濾掉不符合條件的分組,使用having而不是where
** having和where的區(qū)別 **:
** where在數(shù)據(jù)分組前進(jìn)行過(guò)濾,having在數(shù)據(jù)分組后進(jìn)行過(guò)濾,where過(guò)濾的是行,having過(guò)濾的是分組 **
select cust_id, count(*) as orders
from orders
group by cust_id
having count(*) >= 2;
select vend_id, count(*) as num_prods
from products
where prod_price >= 4
group by vend_id
having count(*) >= 2;
分組和排序
Paste_Image.png
select order_num,count(*) as items
from orderItems
group by order_num
having count(*) >= 3
order by items, order_num;
Paste_Image.png