SQL高级查询

2018.09.10

星期一

1.嵌套子查询

      特点与优势:

         使用灵活,可以成为SQL语句的多个部分(子查询作为查询条件,临时表,列使用);

         降低SQL的语句复杂程度,提高SQL语句的可读性。

         作为查询条件使用:

          select * from StuInfo where stuid < (select stuid from StuInfo where stuname='张三')

               PS:在查询条件中使用>,<,=符号后的子查询的结果只能有一个。

         作为临时表使用:

         select  stuname,subject,score  from 

         (select * from StuInfo where stuname='张三')s1,

         (select * from Stumarks where score>80)s2 

         where  s1.stuid=s2.stuid

         作为列使用:

         select  s.*

         (select score from Stumarks where subject='HTML' and s.stuid=Stumarks .stuid )'成绩'

         from StuInfo s

2.聚合技术

      in 与 not in:

         通常在where子句中使用,在in和not in后接的子查询中,可以有多个值出现,但必须只能有一列。

          in/not in (1,3)

          in/not in (select  stuid  from  stumarks  where  subject='java'  and  score>80)

      exists与not exists:

         表示存在与不存在

          exists/not exists (select * from stumarks where stumarks.stuid=stuinfo.stuid)

      some,any与all:

         在SQL查询中,some和any的作用是一样的,表示其中的任何一项,all则表示其中的所有的项。

      compute,compute by 汇总查询:

         select  *  from  stumarks  order  by  stuid  desc  compute  avg(score),sum(score)  by  stuid

3.排序函数

         语法:

                           排序函数  over (【分组子句】排序子句【desc/asc】)

         排序函数:

                           row_number函数生成的排序根据排序子句给出递增连续的序号。

                           rank函数生成的排序根据排序子句给出递增的序号,但存在并列并跳空。

                           dense_rank函数生成的排序根据排序子句给出递增的序号,但存在并列不跳空。

         分组子句:

                           partition  by 

         排序子句:

                           order  by

         例:

                对考生总成绩进行排序

                select DENSE_RANK()
                over(order by sum(score) desc)'排名',stuinfo.stuid'学号',stuname'姓名',sum(score)'总成绩'
                from StuInfo,StuMarks where StuInfo.stuid = StuMarks.stuid
                group by StuInfo.stuid,stuname

4.公式表达式

                with  stuinfo  stumarks (stuid,stuname,s2.score)

                as(select s1.stuid,s1.stuname,s2.score  from  stuinfo s1,stumarks s2  where  s1.stuid=s2.stuid  and  subject='SQL')

                select * from  stuinfo  stumarks

                go           

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值