上次问了一个需要查询一张表按某个字段或多个字段分类的前N条记录,
有人给出了解决的SQL语句:
create table test
(
ID int identity,
areaid int,
score int
)--方法1 利用自增ID 适用于sql2000和2005
select areaid,
score
from test t
where id in(select top 3 id from test where areaid=t.areaid order by score desc)
--方法2 适用于sql2000和2005
select areaid,
score
from test t
where (select count(*) from test where areaid=t.areaid and score>t.score )<3实验后确实可行,
但我不理解这两个语句,请问这两个语句该怎么理解?谢谢
有人给出了解决的SQL语句:
create table test
(
ID int identity,
areaid int,
score int
)--方法1 利用自增ID 适用于sql2000和2005
select areaid,
score
from test t
where id in(select top 3 id from test where areaid=t.areaid order by score desc)
--方法2 适用于sql2000和2005
select areaid,
score
from test t
where (select count(*) from test where areaid=t.areaid and score>t.score )<3实验后确实可行,
但我不理解这两个语句,请问这两个语句该怎么理解?谢谢
解决方案 »
- sql 事务锁表问题!
- 问一下,怎么查询某个外键约束作用在哪个表中
- 简单问题,请帮忙看看
- 再请教一个代码规范问题:字段名列表长,一行写不下,换行时,逗号写在行尾呀,还是写在行头规范呢?
- SQL Server2005的ReportService中连接Oracle数据源时,报表不能传参数,是怎么回事,谢谢了!
- 可以對存儲過程返回紀錄集進行處理嗎
- 在sql server中生成script问题
- 如何提高SQLSERVER的批处理速度?
- 简单问题
- 哪位大虾帮我解道简单的多表查询问题
- SQL语句查询空值问题,请高手解决
- 监控SiYuanLibraryMS数据库中DDL_DATABASE_LEVEL_EVENTS级别的所有事件
select top 3 id from test where areaid=t.areaid order by score desc相同的areaid 取 按score 倒序的前3条
你把这句
select areaid,
score
from test t
where id in(select top 3 id from test where areaid=t.areaid order by score desc)
分别查询下。
select top 3 id from test where areaid=t.areaid order by score descselect areaid,
score
from test t
where id in(......)
id 在子查询中与test表areaid相等的前3里面 就返回值第2个是计算数量
计算子查询中areaid与外面表相等 score比test表大的
score ,(select count(*) from test where areaid=t.areaid and score>t.score )
from test t
--where <3