SQL語句練習(xí)實(shí)例之二——找出銷售冠軍
更新時(shí)間:2011年10月07日 00:27:05 作者:
在公司中,老板走進(jìn)來,要一張每個(gè)地區(qū)銷量前3名的銷售額與銷售員的報(bào)表
復(fù)制代碼 代碼如下:
--銷售冠軍
--問題:在公司中,老板走進(jìn)來,要一張每個(gè)地區(qū)銷量前3名的銷售額與銷售員的報(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,'錢二',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
---以下這種寫法SQL語句會(huì)主動(dòng)把最小的那一個(gè)銷售額的所有行,都自動(dòng)刪除,只能得到比最小銷售額大的數(shù)據(jù)
--如果你的最小銷售額有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
相關(guān)文章
SQL?Server數(shù)據(jù)庫生成與執(zhí)行SQL腳本詳細(xì)教程
為了方便可以把需要連續(xù)執(zhí)行的SQL語句寫到一個(gè)文本文件中,并且用.SQL作為擴(kuò)展名,這種文件叫做SQL腳本文件,下面這篇文章主要給大家介紹了關(guān)于SQL?Server數(shù)據(jù)庫生成與執(zhí)行SQL腳本的相關(guān)資料,需要的朋友可以參考下2023-01-01SqlServer創(chuàng)建自動(dòng)收縮事務(wù)日志任務(wù)的圖文教程
SQL Server數(shù)據(jù)庫存在一個(gè)問題,如果你限制了它的日志文件的大小,那么當(dāng)數(shù)據(jù)庫日志達(dá)到這個(gè)大小的時(shí)候,數(shù)據(jù)庫就會(huì)停止寫入日志,下面這篇文章主要給大家介紹了關(guān)于SqlServer創(chuàng)建自動(dòng)收縮事務(wù)日志任務(wù)的相關(guān)資料,需要的朋友可以參考下2022-09-09sql server編寫通用腳本實(shí)現(xiàn)獲取一年前日期的方法
這篇文章主要介紹了sql server編寫通用腳本實(shí)現(xiàn)獲取一年前日期,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07SQL Server 實(shí)現(xiàn)數(shù)字輔助表實(shí)例代碼
這篇文章主要介紹了SQL Server 實(shí)現(xiàn)數(shù)字輔助表的相關(guān)資料,并附實(shí)例代碼,需要的朋友可以參考下2016-10-10SqlServer 2000、2005分頁存儲(chǔ)過程整理
這篇文章主要介紹了SqlServer 2000、2005分頁存儲(chǔ)過程整理,本文給出了4個(gè)實(shí)現(xiàn)版本,還給出二分分頁過程,需要的朋友可以參考下2015-02-02