飞奔·慢行
===========================================================
mssql里的排序问题
===========================================================
数据表:
DEPT ITEM QTY
1  001  8
1  002  6
1  003  9
1  004  1
2  001  8
2  002  6
2  003  9
2  004  1
3  001  8
3  002  6
3  003  9
3  004  1
怎么样只选择每个DEPT里QTY排名前两名的ITEM
select top 2 * from table order by qty desc,只能选两条记录

----------------------------------------------------------------------------------------------
select 1 dept,'001' item,8 qty
into magic
union all
select 1,'002',6
union all
select 1,'003',9
union all
select 2,'001',8
union all
select 2,'002',6
union all
select 2,'003',9

select * from magic a where qty in (select top 2 qty from magic where dept=a.dept order by qty desc)

----------------------------------------------------------------------------------------------
--或者这样写

select * from magic a where (select count(1) from magic where dept=a.dept and qty>a.qty)<2

----------------------------------------------------------------------------------------------
--一个朋友的答案
declare @linshi table (DEPT int ,ITEM char(10) ,QTY int)
declare @dept int
set @dept=1
while(@dept<=(select max(dept) from magic ))
begin
insert into @linshi select top 2* from magic where dept=@dept order by qty desc
set @dept=@dept +1
end
select * from @linshi

kyle 发表于:2004.12.08 19:17 ::分类: ( dbms ) ::阅读:(567次) :: 评论 (0)

发表评论
标题

在此添加评论
表情符号: smile laughing tongue angry crying sad wassat wink

称呼

邮箱地址(可选)

个人主页(可选)

 authimage


自我介绍
切换风格
新闻聚合
博客日历
文章归档...
最新发表...
最新评论...
博客统计...
Blog信息
网站链接...