徐亚东

您当前位置:YaDong网 >> 一些日志 >> SqlServer相关 >> 浏览文章

SQL Server T-SQL高级查询(二)——嵌套查询

作者:admin   更新日期:2012年06月27日 点击:

Ø 嵌套子查询

子查询是一个嵌套在select、insert、update或delete语句或其他子查询中的查询。任何允许使用表达式的地方都可以使用子查询。子查询也称为内部查询或内部选择,而包含子查询的语句也成为外部查询或外部选择。

# from (select … table)示例

将一个table的查询结果当做一个新表进行查询
select * from (
    select id, name from student where sex = 1
) t where t.id > 2;

上面括号中的语句,就是子查询语句(内部查询)。在外面的是外部查询,其中外部查询可以包含以下语句:

1、 包含常规选择列表组件的常规select查询

2、 包含一个或多个表或视图名称的常规from语句

3、 可选的where子句

4、 可选的group by子句

5、 可选的having子句

 

# 示例

查询班级信息,统计班级学生人生
select *, (select count(*) from student where cid = classes.id) as num 
from classes order by num;

 

# in, not in子句查询示例

查询班级id大于小于的这些班级的学生信息
select * from student where cid in (
    select id from classes where id > 2 and id < 4
);
 
查询不是班的学生信息
select * from student where cid not in (
    select id from classes where name = '2班'
)

in、not in 后面的子句返回的结果必须是一列,这一列的结果将会作为查询条件对应前面的条件。如cid对应子句的id;

 

# exists和not exists子句查询示例

查询存在班级id为的学生信息
select * from student where exists (
    select * from classes where id = student.cid and id = 3
);
 
查询没有分配班级的学生信息
select * from student where not exists (
    select * from classes where id = student.cid
);

exists和not exists查询需要内部查询和外部查询进行一个关联的条件,如果没有这个条件将是查询到的所有信息。如:id等于student.id;

 

# some、any、all子句查询示例

查询班级的学生年龄大于班级的学生的年龄的信息
select * from student where cid = 5 and age > all (
    select age from student where cid = 3
);
 
select * from student where cid = 5 and age > any (
    select age from student where cid = 3
);
 
select * from student where cid = 5 and age > some (
    select age from student where cid = 3
);

 

Ø 聚合查询

1、 distinct去掉重复数据

select distinct sex from student;
select count(sex), count(distinct sex) from student;

 

2、 compute和compute by汇总查询

对年龄大于的进行汇总
select age from student 
where age > 20 order by age compute sum(age) by age;
 
对年龄大于的按照性别进行分组汇总年龄信息
select id, sex, age from student 
where age > 20 order by sex, age compute sum(age) by sex;
 
按照年龄分组汇总
select age from student 
where age > 20 order by age, id compute sum(age);
 
按照年龄分组,年龄汇总,id找最大值
select id, age from student 
where age > 20 order by age compute sum(age), max(id);

compute进行汇总前面是查询的结果,后面一条结果集就是汇总的信息。compute子句中可以添加多个汇总表达式,可以添加的信息如下:

a、 可选by关键字。它是每一列计算指定的行聚合

b、 行聚合函数名称。包括sum、avg、min、max、count等

c、 要对其执行聚合函数的列

compute by适合做先分组后汇总的业务。compute by后面的列一定要是order by中出现的列。

 

3、 cube汇总

cube汇总和compute效果类似,但语法较简洁,而且返回的是一个结果集。

select count(*), sex from student group by sex with cube;
select count(*), age, sum(age) from student where age is not null group by age with cube;

cube要结合group by语句完成分组汇总

SqlServer,高级查询,T-Sql,嵌套查询,YaDong网,徐亚东,亚东网
上一篇:SQL Server T-SQL高级查询(一)
下一篇:SQL Server T-SQL高级查询(三)

网友评论:


生活随笔

SqlServer相关

Web前端

ASP.NET编程

互联网杂谈

我们都是80后

网站建设相关