我有一个名为Orders
的表,其中的数据如下所示:
EMpID OrderValue OrderID 1 100 1 2 167 89 ....
每个empID都有多个订单。 我想要的是以这种形式获得输出
EMPID RANK VALUETOTAL VALUETHISEMPID 1 1 300 100 4 2 300 50\ .....
如果有多个EmpID(s)具有相同的ValueThisEmpID,那么它应该获得相同的排名。
我试过
SELECT EmpID,SUM(val) OVER() as VALUETOTAL,SUM(val) OVER(PARTITION BY EmpID)
如何通过ValueThisEmpID获得等级和排序?
答案 0 :(得分:0)
首先是一些测试数据:
insert into #t values (1, 10, 100)
insert into #t values (1, 20, 101)
insert into #t values (2, 30, 120)
insert into #t values (3, 10, 130)
insert into #t values (3, 10.5, 131)
insert into #t values (4, 100, 140)
您需要两个步骤,一个用于获取empIds及其汇总的订单值。第二步是获得总数和排名:
; with Step1 (EmpId, ValueThisEmpId) as
(select empId, sum(OrderValue)
from #t
group by empId)
select EmpId,
rank() over(order by ValueThisEmpId desc) as "rank",
sum(ValueTHisEmpId) over() as ValueTotal,
ValueThisEmpId
from Step1
这将输出:
4 1 180.50 100.00
1 2 180.50 30.00
2 2 180.50 30.00
3 4 180.50 20.50
如果您不想在排名中出现差距,请使用密集排名:
; with Step1 (EmpId, ValueThisEmpId) as
(select empId, sum(OrderValue)
from #t
group by empId)
select EmpId,
dense_rank() over(order by ValueThisEmpId desc) as "rank",
sum(ValueTHisEmpId) over() as TotalValue,
ValueThisEmpId
from Step1