嵌套子查询:
子查询的优势和特点
使用灵活,可以成为sql语句的多个部分
·子查询作为查询条件使用
·子查询作为临时表使用
降低sql语句的复杂度,提高sql语句的可读性
作为临时表使用
例:select stuname ,subject,score from
(select * from stuinfo where name='李四') s1,
(select * from stumarks where score > 80) s2,
where s1.stuid=s2.stuid
作为查询条件使用
例:select * from stuinfo where stuid <
(select stuid from stuinfo where stuname = '王五')
作为列使用
例:select s.*,(select score stumarks where subject = 'html'
and s.stuid=stumarks.stuid) as '成绩' from stuinfo s
使用in和not in完成子查询
in和not in 通常在where子句中使用,在in和not in
后接的子查询可以多个值出现大半年必须只能有一列
例:select * from stuinfo where stuid in (1,3)
not in和in的用法一样只是意思相反
使用exists 和 not exists子查询
·exists 和 not exists表示存在和不存在的意思
·在语句中会判断exists 和 not exists后接的子句是否存在和是否不存在
·exists 和 not exists用法一样,只是意思相反
例:select * from stuinfo where exists
(select * from stumarks where stumarks.stuid=stuinfo.stuid)
使用some、any、all进行子查询
在sql查询中some、any、all后必须跟子查询
在sql查询中,some和any的作用是一样的,表示其中的任何一项
all则表示其中的所有的项
使用compute和compute by 进行汇总查询
compute 进行汇总计算后查询得到两个结果集,第一个是返回查询语句前面的查询明细
后一个结果集返回汇总结果
需要对结果先进行分组然后进行汇总计算的时候可以使用compute by进行分组汇总查询
排序函数
语法:排序函数 over([分组子句] 排序子句 [desc/asc])
row_number 函数生成的排序根据排序子句给出递增连续的序号
rank 函数生成的排序根据排序子句给出递增的序号,但是存在并列并且跳空
dense_rank函数生成的排序根据排序子句给出递增连续的序号,但是存在并列不跳空
分组子句:partition by 分组列,分组列...
排序子句:order by 排序列,排序列...
例:select dense_rank() over(partition by subject order by score desc),
stuinfo.stuid,stuname,sbject from stuinfo,stumarks where
stuinfo.stuid=stumarks.stuid
公式表达式:
with g_name(stuid,stuname,score)
as
(
select s1.stuid,s1.stuname,s2.score
from stuinfo s1,stumarks s2
where s1.stuid=s2.stuid and subject='sql'
)
select * from g_name
go