设为首页 加入收藏

TOP

一道经典的sql面试题不同的写法
2014-11-24 02:54:42 来源: 作者: 【 】 浏览:3
Tags:一道 经典 sql 试题 不同 写法
一道经典的sql面试题不同的写法
用一条SQL语句 查询出每门课都大于80分的学生姓名,表( #test)如下:
Name Course Mark
张三 语文 81
张三 数学 75
李四 语文 76
李四 数学 90
王五 英语 100
王五 语文 81
create table #test
(
Name varchar(10),
Course varchar(10),
Mark float
)
insert into #test
select '张三', '语文', 81 union
select '张三', '数学', 75 union
select '李四', '语文', 76 union
select '李四', '数学', 90 union 
select '王五', '英语', 100 union 
select '王五', '语文', 81

方法A select distinct Name
from #test A
where not exists(select Course
 from #test
 where Mark < 80 and Name = A.Name)
方法B
select * from #test a where mark > 80 and (select count(*) from #test where name=a.name)= (select count(*) from #test where name=a.name and mark > 80)
方法C
select distinct name from #test a where not exists(select * from #test where a.name=name and mark<80) (我认为这种较好)
方法D
select distinct name from  #test  where 
name not in (
select name from #test where mark<=80
)
方法E
select name,min(mark) from #test group by name having min(mark)>80 
-----66666
DECLARE @test table (  Name varchar(10),  Course varchar(10),  Mark float)  
insert into @test  select   '张三  ',   '语文  ', 81
 union select   '张三  ',   '数学  ', 75 
union select   '李四  ',   '语文  ', 76
 union select   '李四  ',   '数学  ', 90
 union  select   '王五  ',   '英语  ', 100
 union  select   '王五  ',   '语文  ', 81   
SELECT NAME FROM @test GROUP BY name HAVING count(*)=count(case when mark>=80 then 1 else null end) 或者  
SELECT NAME FROM @test GROUP BY name HAVING count(*)=sum(case when mark>=80 then 1 else 0 end)

---方法F
select name from #test group  by name having min(mark)>80 


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇全面接触SQL语法(1) 下一篇SQL-Oracle08sql序列和同义词

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)