SQL语句的总结(SQL进阶教程)

一、case when

case when 函数可使用在group by语句后,进行条件分组

使用sum,count,avg等聚合函数和case when同时使用,可以将行结构数转换为列结构数据;

update条件分支里使用case when,更新工资问题;

case when 语句中可以使用between ,like,<,>,以及in,exist等子查询功能;

case when 本身值可作为条件再次嵌套case when语句中,如输出x,y,z三列中的最大值问题;

key      x        y          z

1          3         4         5

2          6          4        3

3          5          7         5

4          5           2         3

select key,case when case when x>y then x else y end>z

                              then z

                              else case when x>y then x else y end

                              end as max_value

              from table 1

二、自连接

使用自连接查找局部不一致的列:查找a列相同,b列不同的记录,延伸到同名不同姓,同课不同分等问题;

                select * from table t1 inner join table t2 on

                  t1.a=t2.a and t1.b<> t2.b

非等值自然连接解决排序问题:

id            score

1              100

2                80

3                95

4                 85

5                 85

                select t1.score,(select count(t2.score) from table t2 where t2.score>t1.score)+1 as rank      from  table t1 order by rank; (跳过位次)

              t1.score    t2.score    count(t2.score)  rank

                100            -                0                      1

                95          100              1                        2

                85          95,100          2                        3

                85          95,100          2                        3

                80    85,85,95,100      4                        5


              select t1.score,(select count(distinc t2.score) from table t2 where t2.score>t1.score)+1 as rank from  table t1 order by rank; (不跳过位次)                 

              t1.score    t2.score    count(distinct t2.score)    rank

                100            -                0                                    1

                95          100              1                                    2

                85          95,100          2                                    3

                85          95,100          2                                    3

                80    85,85,95,100      3                                    4

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 50个常用的sql语句Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname...
    哈哈海阅读 4,999评论 0 7
  • 说明:以下五十个语句都按照测试数据进行过测试,最好每次只单独运行一个语句。 问题及描述: --1.学生表 Stud...
    lijun_m阅读 5,104评论 0 1
  • Student(S#,Sname,Sage,Ssex) 学生表 Course(C#,Cname,T#) 课程表 S...
    望l阅读 2,490评论 0 0
  • Student(Sid,Sname,Sage,Ssex) 学生表Course(Cid,Cname,Tid) 课程表...
    小炉炉阅读 5,331评论 0 0
  • Student(S#,Sname,Sage,Ssex) 学生表 Course(C#,Cname,T#) 课程表 S...
    忘了呼吸的那只猫阅读 8,025评论 0 8

友情链接更多精彩内容