仅提取最近的 CallSwitch 信息

Pull ONLY Most Recent CallSwitch Info

2 Table 一个带有通用信息,另一个显示我们的 phone 开关信息。我想根据我们的呼叫开关提取最新信息。这是我的 table 结构的示例数据,即使 callswitch table 可能包含同一天的多条记录,我如何才能只提取最新信息?

Table结构:

   Create Table #PhoneSwitch
    (
      PSID int,
      UserID int,
      #Dialed varchar(100),
      LengthofCall int,
      CallDateTime datetime,
      CallOutcome varchar(100)
    )
    Create Table #ResourceTable
    (
      RID int,
      UserID int,
      AddressMain varchar(100),
      PhoneNameFirst varchar(100),
      PhoneNameLast varchar(100),
      PhoneNameCity varchar(100),
      PhoneNameState varchar(100),
      PhoneNameZip varchar(100)
    )

Insert Into #PhoneSwitch Values 
('1', '311', '5555555555', '0',     '03/16/2015', 'No Connect'), 
('2', '311', '5555555555', '0', '03/16/2015', 'No Connect'),
('3', '311', '5555555555', '0', '03/16/2015', 'No Connect'), 
('4', '511',   '5555555555', '0', '03/15/2015', 'No Connect'), 
('5', '511', '5555555555', '0', '03/15/2015', 'No Connect')

Insert Into #ResourceTable Values 
('1','311','123 Nowhere Street', 'Z',   'F', 'Montreal', 'CA', '123'),
('2','311','123 Nowhere Street', 'Z', 'F', 'Montreal','CA',  '123'),  
('3','311','123 Nowhere Street', 'Z', 'F', 'Montreal', 'CA', '123'),
('4','511','623 Nowhere Street', 'A', 'X', 'Montreal', 'CA', '192'), 
('5','511','623 Nowhere Street', 'A', 'X', 'Montreal', 'CA', '192')

这是我试过的查询,但它不只返回交换机的最新信息

Select case 
         when [UserID] LIKE '311' Then 'Sam Smith' 
         when [UserID] Like '511' Then 'Ricky Zefry' 
       end As [User Name], 
       MAX(PS.CallDateTime) As [Call   Date], 
       RT.AddressMain, RT.PhoneNameFirst, RT.PhoneNameLast, 
       RT.PhoneNameCity,   RT.PhoneNameState, RT.PhoneNameZip
FROM #ResourceTable RT
Inner Join #PhoneSwitch ps
On RT.UserID = PS.UserID

编辑 --- 我需要显示两个用户 ID 的最近调用!

您可以使用 ROW_NUMBER() 获取每个 UserID 的最高记录。然后 select 外部查询中的这条记录:

SELECT *
FROM (
   Select case when RT.[UserID] LIKE '311' Then 'Sam Smith' 
               when RT.[UserID] Like '511' Then 'Ricky Zefry' 
          end As [User Name],
          ROW_NUMBER() OVER (PARTITION BY  RT.[UserID] ORDER BY PS.CallDateTime DESC) AS rn,
          PS.CallDateTime As [Call   Date], 
          RT.AddressMain, RT.PhoneNameFirst, RT.PhoneNameLast, RT.PhoneNameCity,   
          RT.PhoneNameState, RT.PhoneNameZip
   FROM #ResourceTable RT
   Inner Join #PhoneSwitch ps On RT.UserID = PS.UserID ) t
WHERE t.rn = 1

SQL Fiddle Demo