【笔试/面试】SQL 经典面试题

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

基本概念

  • (1)any/all,构成 where 子句的条件判断,any:表示或(or)的概念,all:则表示与(and)的概念,这两个关键字的出现是为了语句的简化;

  • (2)先分组再做聚合,逻辑上也应当如此,聚合(取最值)之后便无分组的必要;

    select region, sum(population), sum(area) from bbc group by region;
         
         
    • 1
  • (3)group by having,having 对分组后的数据进行筛选,这是 where 所做不到的;

1. 不使用 min,找出表 ppp 中 num(列)最小的数

select num from ppp where num <= all(select num from ppp);
   
   
  • 1

不可以使用 min 函数,但可以实用 order by 和 limit 相组合呀;

select * from ppp order by num desc limit 1;
   
   
  • 1

举一反三

自然,不使用 max,找出表 ppp 中 num 最大的数:

select num from ppp where num >= all(select num from ppp);select num from ppp order by num limit 1;
   
   
  • 1
  • 2

2. 选择表 ppp 中的重复记录

select * from ppp    where num in (select num from ppp group by num having count(num) > 1);
   
   
  • 1
  • 2

注意,如下的语句只返回单独的一条记录

select * from ppp group by num having count(num) > 1;
   
   
  • 1

举一反三

查询表中出现 四 次的记录,group by having

select * from ppp    where num in (select num from ppp group by num having count(num) = 4);
   
   
  • 1
  • 2

3. 用一条SQL语句查询出每门课都大于80分的学生姓名

name   kecheng   fenshu
张三     语文       81
张三     数学       75
李四     语文       76
李四     数学       90
王五     语文       81
王五     数学       100
王五     英语       90

select distinct name from stu where name not in (select distinct name from stu where fenshu <= 80);
   
   
  • 1

4. 影分身,一表当做两表用

表形式如下: 
Year      Salary 
2000        1000 
2001        2000 
2002        3000 
2003        4000

想得到如下形式的查询结果 
Year      Salary 
2000      1000 
2001      3000 
2002      6000 
2003      10000

sql语句怎么写?

select b.year, sum(a.salary) from hell0 a, hello b where a.year <= b.year group by b.year;
   
   
  • 1

References

[1] SQL经典面试题及答案

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hftytf/article/details/83821599