SQL语句练习实例之二——找出销售冠军

--销售冠军
--问题:在公司中,老板走进来,要一张每个地区销量前3名的销售额与销售员的报表
---
create table salesdetail
(
Area int not null,
Saler nvarchar(20) not null,
SalerId int not null,
Sales money not null
)
insert salesdetail
select 1,'张三',15,3000
union select 1,'赵一',16,3500
union select 1,'钱二',17,4000
union select 1,'孙三',18,5000
union select 1,'李四',19,5000
union select 1,'王五',11,7000
union select 2,'周边一',25,3000
union select 2,'李白',22,4000
union select 2,'张镇东',23,6000
union select 2,'李宁',24,1000
union select 3,'李斯',35,3000
union select 3,'李勇',33,2000
union select 4,'李逵',44,5000
union select 4,'宋江',45,5000
union select 4,'吴用',42,13000
union select 4,'公孙胜',43,23000
union select 5,'阮小二',51,5000
union select 5,'阮小五',52,5000
union select 5,'林冲',53,5000
union select 5,'林莽',54,6000
go
---以下这种写法SQL语句会主动把最小的那一个销售额的所有行,都自动删除,只能得到比最小销售额大的数据
--如果你的最小销售额有3行,最大的只有一行,如地区5所示,只会得到最大的那一行。
--地区4只能得到二行,原因同上。
select * from salesdetail as a
where sales >= (select min(b.sales)
from salesdetail as b where a.Area=b.Area and a.Sales<=b.Sales
--group by sales
having COUNT(distinct b.Saler)<=3)
order by a.Area,a.Sales desc,a.Saler,a.SalerId
go
---使用rank()为每个分区中的每一行分配一个顺序号,如果有重复值,它们都将分配相同的顺序号。
select a.area,a.saler,seq from
(
select area,saler,RANK() over(PARTITION  by area order by sales desc)  as seq from salesdetail
)a where seq<=3
drop table salesdetail

posted @ 2011-10-02 01:17  DotNet菜园  阅读(1009)  评论(0编辑  收藏  举报