数据库查询思路
最近看了些查询方面的习题,对一些习题表示无从下手
比如:查询成绩比该课程平均成绩低的记录。
[解决办法]
[解决办法]
- SQL code
use CSDNgoif (object_id('tempdb..#temp', 'u') is not null) drop table #tempgocreate table #temp( ID int identity, [name] nvarchar(10), score int)insert into #tempselect N'A', 88 union allselect N'A', 99 union allselect N'B', 77goselect * from #temp--SQL:select * from ( select *, avgScore = avg(1.*score) over(partition by name) from #temp) twhere score < avgScore--result:/*ID name score avgScore1 A 88 93.500000*/
[解决办法]
[解决办法]
除了楼上说的,还可以考虑用any、all这些关键字来实现大于所有xxx或者in的部分逻辑
[解决办法]
4楼的答案是正确的, 你的这个问题只能通过这样的方式来解决.
我借花献佛解释下他的太呆.
use CSDN
go
if (object_id('tempdb..#temp', 'u') is not null)
drop table #temp
go
create table #temp
(
ID int identity,
[name] nvarchar(10),
score int
)
上面这些代码是查看表存在不存在, 并创建表的一个操作
insert into #temp
select N'A', 88 union all
select N'A', 99 union all
select N'B', 77
go
插入一些数据.
select * from #temp
测试下数据都OK不.
--SQL:
select * from
(
select
*,
avgScore = avg(1.*score) over(partition by name)
from #temp
) t
where score < avgScore
这里才是你需要的SQL语句. 不解释了 你自己百度一下吧.
--result:
/*
ID name score avgScore
1 A 88 93.500000
*/
另外 这个不是存储过程