计总与排名SUM和RANK函数

准备一些数据:

 

create table [dbo].[salesperformance](
    [id] [int] identity(1,1) not null,
    [salesman] nvarchar(30) not null,
    [orderdate] [date] null,
    [sell]    decimal(18,2) null
 )
go


select [salesman],[orderdate],[sell] from [dbo].[salesperformance]
go

 

salesman    orderdate    sell
s0003    2019-05-12    23800.00
s0008    2019-05-19    66528.00
s0001    2019-05-05    35455.00
s0001    2019-05-18    75220.00
s0003    2019-05-17    33658.00
s0041    2019-05-10    56300.00
s0041    2019-05-11    41811.00
s0003    2019-05-20    26309.00
s0007    2019-05-02    41811.00
s0022    2019-05-26    26309.00
s0032    2019-05-20    20000.00
s0050    2019-05-28    20000.00

 

使用sum和group by统计各个业务员的销售额:

 

select [salesman] as [业务员],month([orderdate]) as [月份], sum([sell]) as [销售量]
from [dbo].[salesperformance]
group by [salesman],month([orderdate])

 

然后使用rank进行排名,看看谁是销售冠军,谁与谁同级:

 

;with [quantityofsale] as
(
    select [salesman] as [业务员],month([orderdate]) as [月份], sum([sell]) as [销售量]
    from [dbo].[salesperformance]
    group by [salesman],month([orderdate])
)

select [业务员],[月份],[销售量],rank() over( order by [销售量] desc) [销售排名]
from [quantityofsale]

 

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐