SQL statement exercise instance 2-find the sales champion

Source: Internet
Author: User

Copy codeThe Code is as follows: -- sales champion
-- Problem: in the company, the boss came in and asked for a report of the sales and sales staff of the top 3 sales in each region.
---
Create table salesdetail
(
Area int not null,
Saler nvarchar (20) not null,
SalerId int not null,
Sales money not null
)
Insert salesdetail
Select 1, 'zhang san ',
Union select 1, 'zhao yi', 16, 3500
Union select 1, 'money 2 ',
Union select 1, 'sunsan ',
Union select 1, 'lily ',
Union select 1, 'wang wu', 11,7000
Union select 2, 'peripheral 1 ',
Union select 2, 'Li Bai ',
Union select 2, 'zhang Zhen Dong ',
Union select 2, 'Li Ning ', 24
Union select 3, 'lies', 35
Union select 3, 'Li Yong ',
Union select 4, 'Li yun', 44,5000
Union select 4, 'songjiang ',
Union select 4, 'wu yong ',
Union select 4, 'Sun sheng', 43,23000
Union select 5, 'employee Kid ',
Union select 5, 'divide small 5 ',
Union select 5, 'lin chong ',
Union select 5, 'limit', 54,6000
Go
--- The following SQL statement will automatically delete all rows with the smallest sales volume and only obtain data larger than the minimum sales volume.
-- If your minimum sales volume has three rows and only one row is the largest, as shown in Area 5, only the row with the largest will be obtained.
-- Region 4 can only get two rows, for the same reason.
Select * from salesdetail as
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
--- Use rank () to assign a sequence number to each row in each partition. If there are duplicate values, they will all be assigned the same sequence number.
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.