简体   繁体   中英

Windowed Functions in SQL Server

I have a table called Orders in which the data looks like this:

EMpID  OrderValue OrderID
1      100        1
2      167        89
....

There are multiple orders for each empID. What I want is to get output in this form

EMPID RANK VALUETOTAL VALUETHISEMPID 
1     1    300        100
4     2    300        50\
.....

If there are multiple EmpID(s) With same ValueThisEmpID then it should get same rank.

I tried

SELECT EmpID,SUM(val) OVER() as VALUETOTAL,SUM(val) OVER(PARTITION BY EmpID)

How can I obtain rank and order it by ValueThisEmpID?

First some test data:

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)

You need two steps, one to get empIds and their summed order value. Step two will be to get the total total and rank:

; 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

This will give output of:

4   1   180.50  100.00
1   2   180.50  30.00
2   2   180.50  30.00
3   4   180.50  20.50

If you don't want gaps in the ranking, use dense rank:

; 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    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM