【SQL解惑】谜题19:销售冠军

一、创建和查询语句
create table SalesData
( district_nbr integer not null,
sales_person char ( 10 )not null,
sales_id integer not null,
sales_amt decimal ( 5 , 2 ) not null)
insert into SalesData ( district_nbr , sales_person , sales_id , sales_amt )
values ( 1 , 'Curly' , 5 , 3.00 ),
( 1 , 'Harpo' , 11 , 4.00 ),
( 1 , 'Larry' , 1 , 50.00 ),
( 1 , 'Larry' , 2 , 50.00 ),
( 1 , 'Larry' , 3 , 50.00 ),
( 1 , 'Moe' , 4 , 5.00 ),
( 2 , 'Dick' , 8 , 5.00 ),
( 2 , 'Fred' , 7 , 5.00 ),
( 2 , 'Harry' , 6 , 5.00 ),
( 2 , 'Tom' , 7 , 5.00 ),
( 3 , 'Irving' , 10 , 5.00 ),
( 3 , 'Melvin' , 9 , 7.00 ),
( 4 , 'Jenny' , 15 , 20.00 ),
( 4 , 'Jessie' , 16 , 10.00 ),
( 4 , 'Mary' , 12 , 50.00 ),
( 4 , 'Oprah' , 14 , 30.00 ),
( 4 , 'Sally' , 13 , 40.00 )
二、查询语句
1、解惑一
方法一:
select *
  from SalesData as s0
  where s0 . sales_amt <= ( select MAX ( s1 . sales_amt )
                                 from SalesData as s1
                                where s0 . district_nbr = s1 . district_nbr
                                  and s0 . sales_amt <= s1 . sales_amt
                               having COUNT ( distinct s1 . sales_person ) <= 3 )
这个的作用:
select MAX ( s1 . sales_amt )
                                 from SalesData as s1
                                where s0 . district_nbr = s1 . district_nbr
                                  and s0 . sales_amt <= s1 . sales_amt
                               having COUNT ( distinct s1 . sales_person )
筛选出每个地区中独立销售额数大于3的且最大的销售额
方法二:
select *
  from SalesData as s0
  where sales_amt >= ( select min ( s1 . sales_amt )
                                 from SalesData as s1
                                where s0 . district_nbr = s1 . district_nbr
                                  and s0 . sales_amt <= s1 . sales_amt
                               having COUNT (*) <= 3 )
  order by s0 . district_nbr , s0 . sales_person , s0 . sales_id , s0 . sales_amt
2、解惑二(OLAP函数)
select s1 . distric_nbr , s1 . sales_person , s1 . rank_nbr
  from ( select district_nbr , sales_person ,
                     RANK ()
                     over ( PARTITION by district_nbr
                           order by sales_amt desc )
              from SalesData )
             as s1 ( distric_nbr , sales_person , rank_nbr )
  where s1 . rank_nbr <= 3







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值