一、知识
之前的操作都是对某一列进行操作,使用”where“来过滤数据。上一课我们学过一个案例
前例:
SELECT
count(vend_id)
from tyqsl2.products
我们虽然能统计这一列的计数,但是如果我们想根据某一行的类型来计量各类不同项的计数。比如以下这张表:
想要根据不同的Vend_id来计算列的数目(用通俗的话就是说想知道BRS01、DLL01、FNG01分别有多少个)。需要用到如下语句:
输出如下:
SELECT vend_id ,
count(vend_id)
from tyqsl2.products
group by vend_id
GROUP BY
某一列数据α可以理解为一个集合A,A内部有N个分组(上例对应解释,即A为Vend_id,A由3个分组BRS01、DLL01、FNG01构成)。GROUP BY α 即按照列上这N个分组进行对应操作。如上例,即按 N分组进行count 运算。(结合这段话,和上面例子对应理解,多思考,会豁然开朗)
HAVING
继续按照上一个例子深入,如果想要得到count计数大于等于3由该怎么操作呢?所以我们引入HAVING关键字,想要过滤掉count计数小于2的写法如下:
SELECT vend_id ,
count(vend_id)
from tyqsl2.products
group by vend_id
having count(vend_id) >=3
having有点where的意思,不过它一般和group 连用,都有过滤的意思。这里有语法规定,where < having < order by(这里的大小表示先后顺序,越大表示出现位置越晚)
混合用例
原表情况:目测第二列知有5个1、5个2、4个3、2个4、2个5。(只是举例,不可能真数表,那也太蠢了。。)所以共有5组,我们想抓计数大于3的order_item该怎么写呢?
相信如果真的看懂了这篇文章,应该能写的出来。具体写法如下:
select order_item,
count(order_item)
from tyqsl2.orderitems
group by 1
having count(order_item) >=3
order by 2
二、课后习题
select order_num,
count(order_num) as order_lines
from tyqsl2.orderitems
group by 1
order by 2
select prod_id,
min(prod_price) as cheapest_item
from tyqsl2.products
group by 1
order by 2
select order_num,
prod_id,
quantity
from tyqsl2.orderitems
where quantity >= 100
select order_num,
prod_id,
item_price * quantity as total_price
from tyqsl2.orderitems
where item_price * quantity >= 1000
select order_num,
prod_id,
item_price * quantity as total_price
from tyqsl2.orderitems
where item_price * quantity >= 1000