|
我们通常用Select fields from table where clause 以及加上group by或order by 来写SQL语句
以前对于要用到聚合结果作条件的情况,我们都用查询嵌套分方法实现的。
这里推荐一个语句
Select fields from table where clause group by fields having sum(field2)或其他聚合函数组成的条件
where 可以实现对当前数据中的字段记录设置条件
group by fields having sum(field2)或其他聚合函数组成的条件 这部分可以对分组聚合函数做条件判断,弥补了用where 不能对当前数据汇总结果的条件判断的缺陷
我们来看一个例子
select 这位同学, 想超越的对象 from
(
select a.学生 as 这位同学,b.学生 as 想超越的对象
from [score$] a, [score$] b
where b.考试日期 = a.考试日期
and b.学生 <> a.学生
and b.数学成绩 - a.数学成绩 > 0
)
group by 这位同学, 想超越的对象
having count(*) =
(select count(*) from (select distinct 考试日期 from [score$]))
上面SQL语句都是实现找每次都考的分数比自己高的人
(select count(*) from (select distinct 考试日期 from [score$])
求不同日期的个数,也就是考试次数
……group by 这位同学, 想超越的对象
having count(*) =
(select count(*) from (select distinct 考试日期 from [score$]))
按这位同学, 想超越的对象分组 次数等于总的考试次数,聚合函数生成的条件
在group 前括号里的查询结果是每次考试,不同本人比的,成绩比自己好的记录集
不可以写成:
select * from
(
select a.学生 as 这位同学,b.学生 as 想超越的对象
from [score$] a, [score$] b
where b.考试日期 = a.考试日期
and b.学生 <> a.学生
and b.数学成绩 - a.数学成绩 > 0
)
group by 这位同学, 想超越的对象
having count(*) =
(select count(*) from (select distinct 考试日期 from [score$]))
在group by 语句中查询字段必需要有分组字段的。
下面写的语句就更漂亮了
select a.学生 as 这位同学, b.学生 as 想超越的对象
from [score$] a, [score$] b
where a.学生 <> b.学生
and a.考试日期 = b.考试日期
group by a.学生, b.学生
having sum(IIf(b.数学成绩 - a.数学成绩 > 0, 1, 0)) = sum(1)
order by a.学生, b.学生 |
评分
-
1
查看全部评分
-
|