黑马程序员之SQL server基础学习笔记(三)
(一)group by
select age, count(*) from student group by age
查询的字段名只能是group by里的,或者是一些聚合函数。上面代码的意思是将一样年龄的放到同一个分组里,并统计每一种年龄有多少人
(二)having
select age, count(*) from student group by age having age<25
select age, count(*) from student where age<25 group by age
大家看一下上面的代码有什么不一样呢?一个是分组后再过滤,一个是过滤后再分组,但得到的结果是一样的。这个例子的情况比较特殊,在大多数情况下where和having和where是不能互换的。having是一定要在group by后面使用的,指的是在字段按照要求分完组后再进行过虑。而where是只能在表里面就开始过滤了,它们三个也可以同时使用,where的优先级最高,其次是group by,最后是having。
(三)top
select top 3 * from student
top是指查询后的数据的前n条。上例中是指所有学生中的前三条。top有很多组合用法,在很多子查询中都会用到
(四)distinct
select distinct age from student
distinct 消除重复的字段,如果有多个字段,则要都重复才会消除。上例中的意思是如果年龄中有相同的,则只显示一个
(五)union
select name,0 from teacher
union all
select name,smoney from student
union 合并两个查询结果,查询的字段要相同,如果字段不一样,要用同类型的补全,如上题所示。
union all 合并时不会去掉重复行。
下面再举一个例子,求工资合计:
select name,tmoney from teacher
union all
select '工资合计',SUM(tmoney) from teacher
这样就能很好地显示结果了

浙公网安备 33010602011771号