本文使用 Zhihu On VSCode 创作并发布
上一节介绍了 group by 语句,可以对表中的某些字段进行聚合操作,如统计每种商品分类的个数。聚合操作完成以后,如何筛选出满足一定条件的数据呢?我们来看一下:
首先统计出每种 product_type 的行数:
select product_type, count(1) as num
from product
group by product_type
然后统计出行数为 4 的 product_type 有哪些?最开始的想法是把 group by 聚合后的结果作为临时表,然后用 where 查询:
select
product_type
from
(
select product_type, count(1)