復(fù)制代碼 代碼如下:
--銷(xiāo)售冠軍
--問(wèn)題:在公司中,老板走進(jìn)來(lái),要一張每個(gè)地區(qū)銷(xiāo)量前3名的銷(xiāo)售額與銷(xiāo)售員的報(bào)表
---
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,'錢(qián)二',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,'張鎮(zhèn)東',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
---以下這種寫(xiě)法SQL語(yǔ)句會(huì)主動(dòng)把最小的那一個(gè)銷(xiāo)售額的所有行,都自動(dòng)刪除,只能得到比最小銷(xiāo)售額大的數(shù)據(jù)
--如果你的最小銷(xiāo)售額有3行,最大的只有一行,如地區(qū)5所示,只會(huì)得到最大的那一行。
--地區(qū)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()為每個(gè)分區(qū)中的每一行分配一個(gè)順序號(hào),如果有重復(fù)值,它們都將分配相同的順序號(hào)。
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
您可能感興趣的文章:- SQL語(yǔ)句練習(xí)實(shí)例之六 人事系統(tǒng)中的缺勤(休假)統(tǒng)計(jì)
- SQL語(yǔ)句練習(xí)實(shí)例之五 WMS系統(tǒng)中的關(guān)于LIFO或FIFO的問(wèn)題分析
- SQL語(yǔ)句練習(xí)實(shí)例之四 找出促銷(xiāo)活動(dòng)中銷(xiāo)售額最高的職員
- SQL語(yǔ)句練習(xí)實(shí)例之一——找出最近的兩次晉升日期與工資額
- SQL語(yǔ)句練習(xí)實(shí)例之三——平均銷(xiāo)售等待時(shí)間
- SQL語(yǔ)句練習(xí)實(shí)例之七 剔除不需要的記錄行