sql 必知必会(四)

十、分组数据

      分组允许把数据分成多个逻辑组,以便能对每个逻辑组进行聚集计算。

①、select column1,count(* ) from table1 group by column1;

      group by 子句指示DBMS分组数据,然后对每个分组而不是整个结果集进行聚集。

      group by注意

②、select vend_id,count(*) as num_prods from products

      where prod_prices >=4 group by vend_id having count(*) >=2

      例子的目的查询具有2个以上,价格4以上的产品的供应商。

      having可以对分组进行过滤,而where是过滤行。仅在有group by的子句中才使用having。

      where在分组前过滤,having在分组后过滤,where排除的行不包含在分组中。

十一、子查询

      作为子查询的select语句只能查询单个列。

      ①、select column1 from table1 where column2 in(select column1 from table2 where column2=value).

      括号中的select称为子查询。

     ②、select column1,column2,(select count(*) from table2 where table2.id=table1.id) as column3

           from table1 order by id.

      此例是子查询结果作为一个计算列。查询table1表中的column1和column2.

      将table2表中id和table1表中id相同的所有列的数目作为计算列返回,列名为column3.

    子查询常用的用法就是用于where子句的in操作符中以及用来填充计算列。

原文地址:https://www.cnblogs.com/zhouxiuquan/p/2299481.html