SQL Update查询中的聚合函数

时间:2016-05-13 13:23:33

标签: sql-server

我有表Emp,由4列组成;

Name   Date        Calls  Supervisor
Alwin  10-05-2016  20     Pramod
Pavan  11-05-2016  10     Steevan
Amit   12-05-2016  12     Raja
Alwin  13-05-2016  15     Sagar

我们需要将所有用户的呼叫加起来并将其置于最近的日期和相应的主管之下,我们每个用户只需要一行。 我们正在寻找的预期结果是

Name   Date        Calls  Supervisor
Pavan  11-05-2016  10     Steevan
Amit   12-05-2016  12     Raja
Alwin  13-05-2016  35     Sagar

请帮帮我。

2 个答案:

答案 0 :(得分:0)

试试这个

select Name, Date, SUM(Calls) from Test
Group By Name, Date

结果:

Name    Date        SumCalls
Alwin   05/10/2016  35
Pavan   05/11/2016  10
Amit    05/12/2016  12

答案 1 :(得分:0)

使用SUM() Over查找每个calls的总Name,并根据最新supervisor使用date窗口函数获取Row_Number() < / p>

;WITH cte 
     AS (SELECT NAME, 
                date, 
                Sum(calls)OVER(partition BY NAME)  AS calls, 
                supervisor, 
                Row_number()OVER(partition BY NAME ORDER BY date DESC) Rn 
         FROM   yourtable) 
SELECT NAME, 
       date, 
       calls, 
       supervisor 
FROM   cte 
WHERE  Rn = 1