27,580
社区成员
发帖
与我相关
我的任务
分享
create table 客户订单表
(姓名 varchar(10),货号 varchar(10),数量 int)
insert into 客户订单表
select '张三','A',10 union all
select '李四','A',100 union all
select '王五','A',5 union all
select '赵六','A',50 union all
select '张三','B',4 union all
select '李四','B',3 union all
select '王五','B',2 union all
select '赵六','B',1 union all
select '李四','C',50 union all
select '张三','D',1000
select a.货号,
a.数量,
a.名次,
case when b.张三订量 is null then null else
(select count(1) from
(select c.姓名,c.货号
from 客户订单表 c
group by c.姓名,c.货号
having max(c.货号)=a.货号 and sum(c.数量)>=b.张三订量) t) end '张三名次',
isnull(b.张三订量,0) '张三订量'
from
(select 货号,
sum(数量) '数量',
row_number() over(order by sum(数量) desc) '名次'
from 客户订单表
group by 货号) a
left join
(select 货号,
sum(数量) '张三订量'
from 客户订单表
where 姓名='张三'
group by 货号) b on a.货号=b.货号
/*
货号 数量 名次 张三名次 张三订量
---------- ----------- -------------------- ----------- -----------
D 1000 1 1 1000
A 165 2 3 10
C 50 3 NULL 0
B 10 4 1 4
(4 row(s) affected)
*/
select
a.*,b.px as 张三名次,b.数量 as 张三订量
from
(select 货号,数量,row_number()over(order by 数量) as 名次 from tb) as a
cross apply
(select 货号,数量,row_number()over(order by 数量) as 名次 from tb where name='张三' and 货号=a.货号) as b
试试这个