仅拉动最近的CallSwitch信息

时间:2015-03-16 20:19:19

标签: sql-server sql-server-2005

2表一个带有通用信息,另一个表示我们的电话开关信息。我想根据我们的呼叫交换机提取最新信息。这是我的表结构的示例数据,即使callwitch表可能包含同一天的多个记录,我如何只提取最新的信息?

表格结构:

   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的最近呼叫!

1 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()获取每UserID的最高记录。然后在外部查询中选择此记录:

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