使用SQL Server返回A列中的数据总和以及B列中的相应名称

时间:2017-10-13 00:56:16

标签: sql-server

这有点棘手。我正在使用T-SQL语言。

我在SQL Server中的当前数据是:每个研讨会下都有研讨会和多个BDM可以预订多个机会。

我需要每次研讨会的“Oppty Booked”总数,但只需要预订率最高的BDM名称。

This the current data

Seminar BDM Name    Oppty Booked
--------------------------------
Broome  Ian         6
Broome  Nas         5
Broome  Kit         4
Broome  Fred        0
Gympie  Sam         16
Gympie  Amanda      2
Gympie  Lidcombe    4

我需要的是:Required Output

Seminar BDM Name    Oppty Booked
--------------------------------
Broome  Ian         15
Gympie  Sam         22

我该怎么做才能得到这个?

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询。阅读RANK

CREATE TABLE #Test
(
Seminar VARCHAR(100),
BDM_Name VARCHAR(100),
Oppty_Booked int
)

insert into #TEst values 
('Broome', 'Ian',6)
,('Broome', 'Nas',5)
,('Broome', 'Kit',4)
,('Broome', 'Fred',0)
,('Gympie', 'Sam',16)
,('Gympie', 'Amanda',2)
,('Gympie', 'Lidcombe',4)

select * from #Test

select  Seminar, BDM_Name, Oppty_Booked
from 
(
select 
Seminar,
BDM_Name,
Rank() OVER (partition by Seminar order by Oppty_Booked desc) as RN,
SUM(Oppty_Booked)OVER (partition by Seminar )  as Oppty_Booked
from #Test
) t
where t.rn=1

答案 1 :(得分:0)

也许是另一种选择

示例

Select Top 1 with ties 
       Seminar
      ,[BDM Name]
      ,[Oppty Booked] = sum([Oppty Booked]) over (Partition By Seminar)
 From  YourTable
 Order By Row_Number() over (Partition By Seminar Order By [Oppty Booked] desc)

<强>返回

Seminar BDM Name    Oppty Booked
Broome  Ian         15
Gympie  Sam         22